Created
May 15, 2014 01:53
-
-
Save tractorcow/3a03e0db5deae54ddad1 to your computer and use it in GitHub Desktop.
How to use ListboxField (multiple selection)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Page with a listbox allowing selection of banners | |
*/ | |
class Page extends SiteTree { | |
private static $has_many = array( | |
'Items' => 'Banner' | |
); | |
public function getCMSFields() { | |
$fields = parent::getCMSFields(); | |
// Make default records (quick hack to get them into the db) | |
$count = Banner::get()->count(); | |
if($count == 0) { | |
Banner::create(array('Title' => 'First'))->write(); | |
Banner::create(array('Title' => 'Second'))->write(); | |
Banner::create(array('Title' => 'Third'))->write(); | |
} | |
$fields->addFieldToTab('Root.List', new ListboxField( | |
'Items', // Name of has_many (or many_many) relation | |
'Items', // Title | |
Banner::get()->map('ID', 'Title')->toArray(), // Get source objects | |
$this->Items()->column('ID'), // Get ids of currectly selected objects | |
null, | |
true // Means make this a multi-select field. | |
)); | |
return $fields; | |
} | |
} | |
class Page_Controller extends ContentController { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey I'll look to work this into docs somehow... where do you think would be appropriate?