CakePHP select default value in SELECT input


Using CakePHP:

I have a many-to-one relationship, let's pretend it's many Leafs to Trees. Of course, I baked a form to add a Leaf to a Tree, and you can specify which Tree it is with a drop-down box ( tag) created by the form helper.

The only thing is, the SELECT box always defaults to Tree #1, but I would like it to default to the Tree it's being added to:

For example, calling would bring up the interface to add a new Leaf to Tree #5. The dropdown box for Leaf.tree_id would default to "Tree 5", instead of "Tree 1" that it currently defaults to.

What do I need to put in my Leaf controller and Leaf view/add.ctp to do this?

7/9/2016 3:27:09 PM

Accepted Answer

You should never use select(), or text(), or radio() etc.; it's terrible practice. You should use input():

$form->input('tree_id', array('options' => $trees));

Then in the controller:

$this->data['Leaf']['tree_id'] = $id;
9/28/2011 6:41:24 PM

In CakePHP 1.3, use 'default'=>value to select the default value in a select input:

$this->Form->input('', array('type'=>'select', 'label'=>'Leaf', 'options'=>$leafs, 'default'=>'3'));

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow