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 example.com/leaf/add/5
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?
$attributes['value']
to set which value should be selected defaultYou should never use
select()
, ortext()
, orradio()
etc.; it's terrible practice. You should useinput()
:Then in the controller:
Assuming you are using form helper to generate the form:
Set the third parameter to set the selected option.
In CakePHP 1.3, use
'default'=>value
to select the default value in a select input:If you are using cakephp version 3.0 and above, then you can add default value in select input using empty attribute as given in below example.
The best answer to this could be
Don't use selct for this job use input instead
like this
Hope it helps.