ZendFramework - How to create optgroup and there option using view helpers?

user285594 picture user285594 · Feb 22, 2012 · Viewed 8.6k times · Source

How do i create this with $this->formSelect() ?

<select multiple>
    <optgroup label="a">
       <option>1</option> 
       <option>2</option>
    </optgroup>
    <optgroup label="b">
       <option>1</option> 
    </optgroup>
</select>

Answer

Mr Coder picture Mr Coder · Oct 12, 2013

In Zend Framework 2 this can be done as follows:

$this->add(array(
        'name'=>'Test',
        'type'=>'Zend\Form\Element\Select',
        'attributes'=>array('type'=>'select','required'=>'required'),
        'options'=>array(
            'label'=>'Test',
            'value_options'=>array('fruits'=>array('label'=>'Fruits','options'=>array('1'=>'Apple','2'=>'Mango')),'animals'=>array('label'=>'Animals','options'=>array('cat'=>'CAT','dog'=>'DOG'))),
            'empty_option'=>'Please Select'
        ),

    ));

please note that an option named empty_options doesn't exist instead empty_option should be used.