Reputation: 173
I am creating an application which tracks signatures form various organizations. I have a simple form which I can pass an ID to, so it will automatically select the right organization. The URL for add looks like this:
/signatures/add/3
The form works well. By passing 3, or any other ID, it automatically selects the right field, because in my view I do:
echo $form->input('organization_id', array('selected' => $this->passedArgs));
I run into my problem when the user forgets to fill out a form element. The form returns the user to:
/signatures/add/
So it doesn't have the right organization selected. It reverts to the default which is 1. Any tips on how I can retain my parameters?
Upvotes: 1
Views: 1211
Reputation: 475
The correct way to set the organization_id to the selected value is to include it in your data array in your controller. Eg
function add($organization_id)
if(!empty($this->data)) {
if($this->Signature->save($this->data)) {
$this->setFlash('Save successful')
$this->redirect(array('action' => 'index'))
} else {
$this->setFlash('Please review the form for errors')
}
}
if($organization_id) {
$this->data['Signature']['organization_id'] = $organization_id;
}
}
Then in your view simply put
echo $form->create('Signature', array('action' => 'add'))
echo $form->input('organization_id')
and it will automatically insert the organization_id value from the the controllers data.
Upvotes: 0
Reputation: 173
Thanks Galen. You actually pointed me in the right direction. I realized that my form wanted to save the state of the organization, but I over-wrote it when I did this:
echo $form->input('organization_id', array('selected' => $this->passedArgs));
So what I do now instead is:
if (!empty($this->passedArgs)) {
echo $form->input('organization_id', array('selected' => $this->passedArgs));
} else {
echo $form->input('organization_id');
}
And it does the trick.
Upvotes: 0
Reputation: 30170
I don't know much about cake but it looks like the action of the form is /signatures/add/
If you add the id to the form action so it reads action="signatures/add/{ID}" in the view it should go back to that organizations page
Upvotes: 1