argenkiwi
argenkiwi

Reputation: 2427

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:

Upvotes: 4

Views: 3304

Answers (2)

AudifaxDev
AudifaxDev

Reputation: 1

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

Here is 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);
    }
}

Upvotes: 0

Piksel8
Piksel8

Reputation: 1428

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.

Upvotes: 10

Related Questions