nickspiel
nickspiel

Reputation: 5630

SilverStripe convertDataObjectSet is stripping additional properties

I am attempting to add the 'AbsoluteLink' property to each DataObject in a DataList and then convert the list to JSON with JSONDataFormatter::convertDataObjectSet().

I have the following function:

public function json() {
    $data      = ResourceCentreArticlePage::get()->filter('ShowInMenus', '1')->filter('ShowInSearch', '1')->sort('Created', 'DESC');
    $pageArray = new ArrayList();

    foreach ($data as $page) {
        $page->AbsoluteLink = $page->AbsoluteLink();
        $pageArray->push($page);
    }

    // If I dump out the content of $pageArray here the object has the AbsoluteLink property  

    $jsonFormatter = new JSONDataFormatter();
    $jsonData      = $jsonFormatter->convertDataObjectSet($pageArray);

    // If I dump out the content of $jsonData here there is no AbsoluteLink property

    $this->response->addHeader("Content-type", "application/json");

    return $jsonData; 
}

The problem:

The AbsoluteLink property is removed after running the $pageArray through the convertDataObjectSet method.

What am I missing?

Upvotes: 1

Views: 187

Answers (1)

Olli Tyynelä
Olli Tyynelä

Reputation: 576

Using $jsonFormatter->setCustomAddFields(); will help here.

Add the following to the Page class:

public function getMyAbsoluteLink() {
    return $this->AbsoluteLink();
}

For example to the Page.php:

class Page extends SiteTree {
    public function getMyAbsoluteLink() {
        return $this->AbsoluteLink();
    }
}

And use that "magic field" like this:

public function json() {
    $pages = Page::get()
        ->filter('ShowInMenus', '1')
        ->filter('ShowInSearch', '1')
        ->sort('Created', 'DESC');

    $jsonFormatter = new JSONDataFormatter();
    // add your custom field
    $jsonFormatter->setCustomAddFields(["MyAbsoluteLink"]);
    $jsonData = $jsonFormatter->convertDataObjectSet(
        $pages
    );

    return $jsonData;
}

Note the $jsonFormatter->setCustomAddFields(["MyAbsoluteLink"]); and I removed the array manipulation.

Also I removed your array manipulation. How the convertDataobjectSet function works it seems you can't amend the objects before it runs.

Upvotes: 1

Related Questions