Search code examples
cakephpcakephp-2.x

Cakephp option tag attributes


In the view:

echo $this->Form->input('Ingredient');

The above populate multiple select list that HTML output as:

<select name="data[Ingredient][Ingredient][]" option="hh" multiple="multiple" id="IngredientIngredient">
<option value="1" selected="selected">Tomato</option>
<option value="2">Spaghetti </option>
<option value="3" selected="selected">Salt</option>
</select>

What I need to know is how to add attributes to the generated <option> tag?


Solution

  • Use the controller to pass selected values:

    if ($this->request->is('post') {
        // save form
    } else {
        $this->request->data['Incredient']['Incredient'] = $ids;
    }
    

    See here

    To add additional attributes like classes you just need to make it a deeper array and you can pass those:

    $options = array(
        1 => 'One', 
        2 => array('name' => 'Two', 'value' => 2,  'class' => 'extra'), 
        3 => 'Three');
    
    echo $this->Form->input('test', array('type' => 'select', 'options' => $options));
    

    The result:

    <div class="input select">
        <label for="ModelTest">Test</label>
        <select name="data[Model][test]" id="ModelTest">
            <option value="1">One</option>
            <option value="2" class="extra">Two</option>
            <option value="3">Three</option>
        </select>
    </div>
    

    See this