Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverstripe: CMS Pages as JSON?

I am working on a Silverstripe project and I would like to have a simple way to present the content of a CMS generated Page (or subtype of Page) as JSON.

Ideally, I would like to append "/json" at the end of the route, or send a parameter via post (json=true) and obtain a response in JSON format.

I tried adding an action to my CustomPage_Controller class like this:

public static $allowed_actions = array('json');
public function json(SS_HTTPRequest $request) {
    // ...
}

But I cannot figure out how to make that work:

  • What URL/Route should I use?
  • How do I get the content of the page?
like image 826
argenkiwi Avatar asked Dec 26 '22 00:12

argenkiwi


1 Answers

You're on the right track. You'd simply do something like this in your json action:

public function json(SS_HTTPRequest $request) {

    $f = new JSONDataFormatter();
    $this->response->addHeader('Content-Type', 'application/json');
    return $f->convertDataObject($this->dataRecord);

}

Or for specific fields you could do this:

public function json(SS_HTTPRequest $request) {

    // Encode specific fields
    $data = array();
    $data['ID'] = $this->dataRecord->ID;
    $data['Title'] = $this->dataRecord->Title;
    $data['Content'] = $this->dataRecord->Content;

    $this->response->addHeader('Content-Type', 'application/json');
    return json_encode($data);

}

If you put the above inside the controller in your Page.php file and all your other pages extend Page_Controller then you should be able to go to http://mydomain/xxxx/json and get the JSON output for any page.

like image 190
Shane Garelja Avatar answered Jan 12 '23 03:01

Shane Garelja