Version: current

     1 <?php
     2 /**
     3  * Grouped dropdown, using <optgroup> tags.
     4  *
     5  * $source parameter (from DropdownField) must be a two dimensional array.
     6  * The first level of the array is used for the <optgroup>, and the second
     7  * level are the <options> for each group.
     8  *
     9  * Returns a <select> tag containing all the appropriate <option> tags, with
    10  * <optgroup> tags around the <option> tags as required.
    11  *
    12  * @package forms
    13  * @subpackage fields-basic
    14  */
    15 class GroupedDropdownField extends DropdownField {
    16
    17     function Field() {
    18         // Initialisations
    19         $options = array();
    20         foreach($this->getSource() as $value => $title) {
    21             if(is_array($title)) {
    22                 //$options .= "<optgroup label=\"$value\">";
    23                 $items = array();
    24                 foreach($title as $value2 => $title2) {
    25                     $selected = ($value2 == $this->value);
    26                     //$options .= "<option$selected value=\"$value2\">$title2</option>";
    27                     $items[] = new ArrayData(array(
    28                         'Value' => $value2,
    29                         'Title' => Convert::raw2xml($title2),
    30                         'Selected' => $selected,
    31                     ));
    32                 }
    33                 $options[] = new ArrayData(array(
    34                     'Value' => $value,
    35                     'Items' => new DataObjectSet($items),
    36                 ));
    37                 //$options .= "</optgroup>";
    38             } else { // Fall back to the standard dropdown field
    39                 $selected = ($value == $this->value);
    40                 $options[] = new ArrayData(array(
    41                     'Value' => $value,
    42                     'Title' => Convert::raw2xml($title),
    43                     'Selected' => $selected,
    44                 ));
    45             }
    46         }
    47         $attributes = array(
    48             'class' => ($this->extraClass() ? $this->extraClass() : ''),
    49             'id' => $this->id(),
    50             'name' => $this->name,
    51             'tabindex' => $this->getTabIndex(),
    52         );
    53         if($this->disabled) $attributes['disabled'] = 'disabled';
    54         return $this->createTag('select', $attributes, new DataObjectSet($options));
    55
    56
    57         return "<select $classAttr name=\"$this->name\" id=\"$id\">$options</select>";
    58     }
    59 }
    60
    61 ?>

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -