views:

4570

answers:

3

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?

+1  A: 

assuming you are using form helper to generate the form.

select(string $fieldName, array $options, mixed $selected, array $attributes, boolean $showEmpty)

set the third parameter to set selected option.

Funky Dude
Hey, I have the following code: $options=array('1'=>'opt1','2'=>'opt2','3'=>'opt3'); echo $form->select('Fieldname',$options , ??? ,array(),false);whats the format for the 3rd parameter to set the selected item? I can't seem to get it right.
smchacko
it should be the value of the selected option
Funky Dude
+2  A: 

You should never use select(), or text(), or radio() etc, its terrible practice. You should use input().

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

Then in the controller:

$this->data['Leaf']['tree_id'] = $id;

Miles Johnson
I'm not sure about "terrible practice"
SeanDowney
+1  A: 

the third parameter should be like array('selected' =>value)

Renjith Chacko