CakePHP pre populate select box based on existing selection on related model
I am trying to pre-populate this State select box with the existing selection when editing records. in a related model.
plan_details/view.ctp
echo $this->Form->input('State',array('emp开发者_Python百科ty' => false,'options' => $state));
plan_details_controller view function:
$state = $this->PlanDetail->Plan->State->find('list');
$this->set(compact('state', $state));
debug($state);
Array output in view.ctp (as expected):
Array
(
[1] => Oregon
[2] => Washington
)
My select box above defaults to 1 in the array. I need it to default to the already existing selected value.
For example, when I added a record and a selected Washington(2), then when viewing my edit screen, the pre-selected value should be Washington with value 2.
I'm stuck and cracking at this for a while. Any idea what I am doing wrong?
If you are editing a page you need to set $this->data to auto populate it. Within your edit action
if (empty($this->data)) {
$this->data = $this->PlanDetail->read(null, $id);
}
This should read in the record then ( note the plural )
$states = $this->PlanDetail->Plan->State->find('list');
$this->set(compact('states'));
In your form it should read
echo $this->Form->input('Plan.state_id',array('empty' => false));
I find your approach a bit confusing but the above should work. Is this form for editing a Plan, PlanDetail or both
精彩评论