views:

474

answers:

3

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?

A: 

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

Galen
A: 

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.

Ry
glad i could help
Galen
Although this will work as expected, I'd recommend using named params for optional params. When I see "/signatures/add/3" I don't really know what "3" is. If it were "/signatures/add/organization:3" it is much clearer. Not to mention how this will make your life easier if you ever decide to pass more params: "/signatures/add/organization:3/type:2". Take a look at the cake docs for more info if you haven't used named params before.
dr Hannibal Lecter
A: 

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.

thief