BaronGrivet
BaronGrivet

Reputation: 4424

How to return JSON by default with Silverstripe Controller?

We have a class that extends \PageController & has an allowed action to return JSON. Here's some example code:

class CustomController extends PageController
{
  private static $allowed_actions = array(
    'json'
  );

  public function json(HTTPRequest $request)
  {
    $data['ID'] = $this->ID;
    $data['Title'] = $this->Title;
    $data['Content'] = $this->Content;
    $this->response->addHeader('Content-Type', 'application/json');
    return json_encode($data);
  }
}

When https://www.example.com/custom/json is called it returns a JSON object containing some of the page information.

What is the best way to have this Controller return JSON by default?

In the above example we wanthttps://www.example.com/custom to return a JSON object.

Upvotes: 1

Views: 914

Answers (1)

BaronGrivet
BaronGrivet

Reputation: 4424

It turned out all I needed to do was change the method name from json to index:

public function index(HTTPRequest $request)
{
  $data['ID'] = $this->ID;
  $data['Title'] = $this->Title;
  $data['Content'] = $this->Content;
  $this->response->addHeader('Content-Type', 'application/json');
  return json_encode($data);
}

Upvotes: 2

Related Questions