How to set the disabled attribute as disabled on the first <option> of a Zend Framework 2 form

php, zend-form, zend-framework2

Solution

If I remember correctly you need to format the options array slightly differently:

$options = array(
    array('value' => '0', 'label' => ' Please Select an Attribute', 'disabled' => 'disabled'),
    array('value' => '1', 'label' => ' Attribute 1'),
    array('value' => '2', 'label' => ' Attribute 2')
);

Disabled is one of the valid attributes.

Problem

I´m developing an application using Zend Framework 2 and I´m using two select multiple boxes. The first is populated with data from the data base, the second is empty. I intend to set the disabled attribute as "disabled" in the first option of both selects. This way the first options will be unusable and un-clickable. Therefor a user will not be able to pass those first options from one select to the other while using the add/remove buttons. Select 1 ``` <select id="AttributesId" multiple="multiple" size="7" title="Select an Attribute" name="idAttributes[]"> <option value="0">Please Select an Attribute</option> <option value="1"> Attribute 1</option> <option value="2"> Attribute 2</option> </select> ``` Select 2 ``` <select id="SelectedAttributesId" multiple="multiple" size="7" title="Selected Attributes" name="selectedAttributes[]"> <option value="0">Current Selection</option> </select> ``` The php code that generates both selects on ZF2 is: (...) ``` public function __construct ($em = null) { parent::__construct("typeset"); $this->setAttribute("method", "post") ->setAttribute("class", "contact-form"); if(null !== $em) { $this->setEntityManager($em); } $em = $this->getEntityManager(); $query = $em->createQuery("SELECT a.idAttribute, a.internalName FROM ProductCatalog\Entity\Attribute\Attribute a ORDER BY a.internalName ASC"); $attributes = $query->getResult(); $select = new Element\Select('idAttributes'); $select->setAttribute('title', 'Select an Attribute') ->setAttribute('size', 7) ->setAttribute('multiple', 'multiple') ->setAttribute('id', 'AttributesId'); $selected = new Element\Select('selectedAttributes'); $selected->setAttribute('title', 'Selected Attributes') ->setAttribute('size', 7) ->setAttribute('multiple', 'multiple') ->setAttribute('id', 'SelectedAttributesId'); $labelIdAttributes = 'Attributes List: '; $labelSelectedAttributes = 'Selected Attributes List: '; $options[0] = 'Please Select an Attribute'; ``` // this followin line doesn´t work but you can get an idea of what I need with it //$options[0]->setAttribute('deselect', 'deselect'); ``` foreach ($attributes as $key => $value) { $options[$value['idAttribute']] = $value['internalName']; } $selectedOptions[0] = 'Current Selection'; $select->setLabel($labelIdAttributes) ->setValueOptions($options); $selected->setLabel($labelSelectedAttributes) ->setValueOptions($selectedOptions); $this->add($select); $this->add($selected); (...) ```

Original source