5121 Posts in 1527 Topics by 1119 members
|
Page:
1
|
Go to End | |
| Author | Topic: | 356 Views |
-
[Solved] Populating a DropDownField with Children

16 May 2012 at 7:56pm Last edited: 16 May 2012 7:59pm
For a blog/magazine style site with Posts organized into Categories.
Categories may only contain Posts as child pages.
Each Category would have one featured Post at any one time, selectable in the CMS.
So, in the Category class I have this:
static $allowed_children = array('Post');
static $has_one = array(
'FeaturedPost' => 'Post'
);In the admin for a Category, I want to populate a dropdown with all of the Category's child Posts, and save the dropdown selection into FeaturedPost. Right now in getCMSFields with Category, I have this:
public function getCMSFields()
{
$fields = parent::getCMSFields();
$children = $this->Children();
$featured_field = new DropDownField('FeaturedPost', 'FeaturedPost', $children);
$fields->addFieldToTab('Root.Content.Main', $featured_field);
return $fields;
}The DropDownField populates with the right number of Posts, but it doesn't save into the FeaturedPost relationship, or display the titles of the Posts.
Any help? Thanks in advance.
-
Re: [Solved] Populating a DropDownField with Children

16 May 2012 at 8:14pm
With the has_one you need to append ID to the field name:
$featured_field = new DropDownField('FeaturedPostID', 'FeaturedPost', $children);
Though $children will be a list of pages, so perhaps you want to ensure you only get Post types in $children.
$children = DataObject::get("Post", "ParentID = '". $this->ID ."'");
-
Re: [Solved] Populating a DropDownField with Children

16 May 2012 at 8:31pm
Thanks for the reply Will.
How do I also get the Post titles to be listed in the DropDownField? Right now it displays:
Post
Post
Post
etc...And it doesn’t seem to save a particular Post as the FeaturedPost when you publish the page. How do you bind the DropDownField to a particular $has_one relationship?
-
Re: [Solved] Populating a DropDownField with Children

16 May 2012 at 8:40pm
I thought it would have done this by default but you may need to call map() (http://API.silverstripe.org/2.3/sapphire/model/DataObjectSet.html#methodmap)
$children = DataObject::get("Post", "ParentID = '". $this->ID ."'");
if($children) $children = $children->map("ID", "Title");$featured_field = new DropDownField('FeaturedPostID', 'FeaturedPost', $children);
How do you bind the DropDownField to a particular $has_one relationship?
Well the first argument to DropDownFIeld 'FeaturedPostID' should map to your $has_one = array('FeaturedPost'). Have you done a dev/build?flush=1 then reloaded the admin?
-
Re: [Solved] Populating a DropDownField with Children

16 May 2012 at 8:43pm
That works perfectly. Will, you are a legend. Thank you.
| 356 Views | ||
|
Page:
1
|
Go to Top |


