Silverstripe: CMS Pages as JSON?

I am working on a Silverstripe project, and I would like to have an easy way to present the contents of the generated CMS page (or page subtype) as JSON.

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

I tried to add an action to my CustomPage_Controller class as follows:

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

But I canโ€™t figure out how to do this:

  • Which URL / route should I use?
  • How to get page content?
+4
source share
2 answers

You are on the right track. You would just do something similar 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 certain fields you can 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 into the Page.php file, and all other pages are expanded by Page_Controller , then you can go to http://mydomain/xxxx/json and get JSON output for any page.

+10
source

Shane's answer was useful, however I needed to output all pages from the route, not just the current record.

Here's how I managed to do this:

 <?php class Page_Controller extends ContentController { private static $allowed_actions = [ 'index', ]; public function init() { parent::init(); // You can include any CSS or JS required by your project here. // See: http://doc.silverstripe.org/framework/en/reference/requirements } public function index(SS_HTTPRequest $request) { $results = []; $f = new JSONDataFormatter(); foreach (Article::get() as $pageObj) { $results[] = $f->convertDataObjectToJSONObject($pageObj); } $this->response->addHeader('Content-Type', 'application/json'); return json_encode($results); } } 
0
source

Source: https://habr.com/ru/post/1489601/


All Articles