Skip to content

Instantly share code, notes, and snippets.

@tractorcow
Created May 15, 2014 01:53
Show Gist options
  • Save tractorcow/3a03e0db5deae54ddad1 to your computer and use it in GitHub Desktop.
Save tractorcow/3a03e0db5deae54ddad1 to your computer and use it in GitHub Desktop.
How to use ListboxField (multiple selection)
<?php
/**
* For cool guy @BenENewton
*/
class Banner extends DataObject {
private static $db = array(
'Title' => 'Varchar'
);
private static $has_one = array(
'Parent' => 'Page'
);
}
<?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 {
}
@camfindlay
Copy link

Hey I'll look to work this into docs somehow... where do you think would be appropriate?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment