b4rt3kk b4rt3kk - 1 year ago 90
PHP Question

Zend2 Form - set attributes to options in select element

I wonder how to add some attributes to select's options in Zend 2. My form element looks like this:

$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'brand_name',
'options' => array(
'label' => 'Choose brand',
'value_options' => $this->getBrands(),
),
));


So it's populate select looking similar to this:

<select name="brand_name"><option value="1">aaaa</option></select>


But I want to achieve something like this:

<select name="brand_name"><option value="1" class="test">aaaa</option></select>


And the classes should be different, depends on particular option. Is it possible? Why am I trying this? I need to add jquery plugin - chained which needs classes for options.

Answer Source

I've found a solution, array of parent select value_options should look like this:

foreach ($data as $item) {
        $models[] = array(
          'label' => $item->model_name, 
          'attributes' => array('class' => $item->id_brand_list), 
          'value' => $item->id);
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download