CakePHP: Setting default value on a select with optgroups

15,820

Solution 1

you might try it like this:

echo $this->Form->input('group_id', array('type'=>'select','default'=>'2'));

leading to the following HTML being generated:

<option value="2" selected="selected">Managers</option>

Now option two is shown instead any other one.

Solution 2

dont use "value" or "selected" etc. this will break your forms in POST. if you must use the view level, use "default".

a better way is to set them from the controller:

if ($this->RequestHandler->is('post')) {
    ...
} else {
    $this->data['Model']['field'] = 2; // e.g.
}

see http://www.dereuromark.de/2010/06/23/working-with-forms/ for details

Solution 3

echo $this->Form->input('point', array(
    'label'=>'',
    'options'=>$list_of_options,
    'value'=>$default_value,
    'empty'=>'--select--', 
    'onchange'=>'some_action();' 
  )
);
Share:
15,820
Chaim
Author by

Chaim

Updated on June 28, 2022

Comments

  • Chaim
    Chaim almost 2 years

    On a normal select, with no optgroups, the following code in CakePHP would make a value the default one:

    'selected' => $value

    Once I have optgroups (a select tag with headings) how do I set a default value? The previous code doesn't seem to work.

  • D.Dimitrioglo
    D.Dimitrioglo almost 9 years
    Thank you for this 'empty'=>'--select--', you saved my day!