add disabled (and selected) option to select item with form helper

Rien C. picture Rien C. · Nov 4, 2010 · Viewed 17.6k times · Source

hi I'm trying to add a disabled option to a select box with the form helper I use this code to generate an extra empty field, but I want this field disabled.

echo $this->Form->input('User.usertype_id',array('type'=>'select', 'empty'=>'usertype');

this generates:

<div class="input select">
    <label for="UserUsertypeId">Usertype</label>
    <select name="data[User][usertype_id]" id="UserUsertypeId">
        <option value="">usertype</option>
        <option value="1">athlete</option>
        <option value="2">trainer</option>
    </select>
</div>

but I want this:

<div class="input select">
    <label for="UserUsertypeId">Usertype</label>
    <select name="data[User][usertype_id]" id="UserUsertypeId">
        <option value="" disabled="disabled" selected="selected">usertype</option>
        <option value="1">athlete</option>
        <option value="2">trainer</option>
    </select>
</div>

Is there any way to do this simply, or should I just use some js?

Answer

stevelove picture stevelove · Nov 4, 2010

If you know the options in advance, you can build the $options array to use in the select menu. This should give you exactly what you want:

$options = array(
            array(
                'name' => 'usertype',
                'value' => '',
                'disabled' => TRUE,
                'selected' => TRUE
            ),
            'athlete',
            'trainer'
            );

echo $this->Form->input('User.usertype_id', array('type' => 'select', 'options' => $options));

Or possibly this might work, but I haven't tested it either:

echo $this->Form->input('User.usertype_id', array('type' => 'select', 'empty'=> array('text' => 'usertype', 'selected' => TRUE, 'disabled' => FALSE)));