我正在尝试添加' AbsoluteLink'属性到DataList中的每个DataObject,然后使用JSONDataFormatter::convertDataObjectSet()
将列表转换为JSON。
我有以下功能:
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;
}
问题:
通过$pageArray
方法运行convertDataObjectSet
后,将删除AbsoluteLink属性。
我错过了什么?
答案 0 :(得分:1)
使用$jsonFormatter->setCustomAddFields();
会有所帮助。
将以下内容添加到Page类:
public function getMyAbsoluteLink() {
return $this->AbsoluteLink();
}
例如到Page.php:
class Page extends SiteTree {
public function getMyAbsoluteLink() {
return $this->AbsoluteLink();
}
}
并使用"魔术场"像这样:
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;
}
注意$jsonFormatter->setCustomAddFields(["MyAbsoluteLink"]);
并删除了数组操作。
我也删除了你的数组操作。 convertDataobjectSet
函数的工作原理似乎无法在对象运行之前对其进行修改。