Silverstripe DataObjects as Pages Part 2 tutorial - Admin Checkbox

妖精的绣舞 提交于 2020-01-06 08:38:21

问题


I'm using the code from DataObjects as Pages 2, so you can choose one to many categories for each product you created under Product tab in admin.

My question is how can I show the parental pages'(it is called ProductsList.php) titles for the categories? Please see the image for details

Or here is the explain: Because all my Category pages are under one or more parents, and some Categories pages are repeated on the site eg Toyota and Honda. I'd like the parents page's titles to show eg Sale and Rental under the Category check boxes, so that the admin person know which repeated categories to choose.

Here is some related code for the Categories check boxes field:

 //Relate to the category pages
  static $belongs_many_many = array(
    'Categories' => 'CategoryPage'
  );

 //Categories
    $Categories = DataObject::get('CategoryPage');
    $fields->addFieldToTab("Root.Categories", new CheckboxsetField('Categories', 'Categories', $Categories));

I'm trying to figure my way through SS, so any help is appreciated.

Thanks a lot.

Sam

Edit/Update:

I managed to make Categories tab to show as Parent-Child eg Sale-Toyota, Sale-Honda, Rental-BMW, Rental-Toyota using the code below. However they are all displayed disorderly/randomly. Any suggestions on how to group them properly eg all the Sales are together and all the Rentals are together?

Code: Add below code to CategoryPage.php

function CheckboxSummary(){
    return $this->Parent()->Title . ' - ' . $this->Title;
}

And add $Categories->map('ID', 'CheckboxSummary') to the option for the checkboxset in Product.php

 $Categories = DataObject::get('CategoryPage'); 
 $fields->addFieldToTab("Root.Categories", new CheckboxsetField('Categories', 'Categories', $Categories->map('ID', 'CheckboxSummary')));

Thanks:)


回答1:


you could build one checkboxset per 'parent page' (make sure to have the proper URLSegment set):

$salePage = DataObject::get_one('Page', "URLSegment = 'sale'");
$Categories = $salePage->Children();
$fields->addFieldToTab("Root.Categories", new CheckboxsetField('Categories', 'Sale', $Categories));

UPDATE

concerning the solution using 'CheckboxSummary' you mention in your updated question, the simplest solution is using 'asort()' to sort the array you're feeding to the CheckboxSetField:

$Categories = DataObject::get('CategoryPage');
$map = $Categories->map('ID', 'CheckboxSummary');
asort($map);
$fields->addFieldToTab("Root.Categories", new CheckboxsetField('Categories', 'Categories', $map)); 

for what asort() does, see http://php.net/manual/en/function.asort.php



来源:https://stackoverflow.com/questions/9072191/silverstripe-dataobjects-as-pages-part-2-tutorial-admin-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!