Home » Php » php – CakePHP: Setting default value on a select with optgroups

php – CakePHP: Setting default value on a select with optgroups

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

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.

Answer:

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

Answer:

echo $this->Form->input('point', array(
    'label'=>'',
    'options'=>$list_of_options,
    'value'=>$default_value,
    'empty'=>'--select--', 
    'onchange'=>'some_action();' 
  )
);