ListboxField example that uses an arbitrary array of values
I've often used ListBox when dealing with DataObjects as the values being selected, it's a little undocumented how to deal with just an arbitrary array... so here is an example for that. The key to understanding the difference is that you must use the consistent index to the array - but also for robustness store the names because it is just that list of names (or tags) that is what I need...
class MyDataObject extends DataObject { private static $db = array( 'Name' => 'Varchar(255)', 'MyCSVField' => 'Varchar(255)', ); function MyValues(){ return array('one','two','three','four'); } function getCMSFields(){ $fields = parent::getCMSFields(); $arrSelectedNames = explode(',',$this->MyCSVField); $arrSelectedIndexes = array(); foreach($this->MyValues() as $i => $name) if (in_array($name,$arrSelectedNames)) $arrSelectedIndexes[] = $i; $fields->insertAfter( 'MyCSVField', ListboxField::create('MyCSVFieldListboxField','Select',$this->MyValues()) ->setMultiple(true) ->setValue($arrSelectedIndexes) ); return $fields; } public function onBeforeWrite() { parent::onBeforeWrite(); $arrValues = $this->MyValues(); $this->MyCSVField = ''; foreach(explode(',',$this->MyCSVFieldListboxField) as $i) $this->MyCSVField .= $arrValues[$i].','; $this->MyCSVField = substr($this->MyCSVField, 0, -1); } }
Post your comment
Comments
No one has commented on this page yet.
RSS feed for comments on this page | RSS feed for all comments