Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Customising the CMS

[Solved] Populating a DropDownField with Children


5 Posts   610 Views

Mr. Neave

16 May 2012 at 7:56pm (Last edited: 16 May 2012 7:59pm), Community Member, 8 Posts

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.


16 May 2012 at 8:14pm Forum Moderator, 5511 Posts

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 ."'");

Mr. Neave

16 May 2012 at 8:31pm Community Member, 8 Posts

Thanks for the reply Will.

How do I also get the Post titles to be listed in the DropDownField? Right now it displays:

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?


16 May 2012 at 8:40pm Forum Moderator, 5511 Posts

I thought it would have done this by default but you may need to call map() (

$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?

Mr. Neave

16 May 2012 at 8:43pm Community Member, 8 Posts

That works perfectly. Will, you are a legend. Thank you.