tags:

views:

304

answers:

2

I'm sure this sort of problem must be common in cakephp (which I've recently started using), but I haven't managed to find a clear answer.

In my database I have, among others, tables called customers and contacts, in a one-to-many relationship (Customer hasMany Contact; Contact belongsTo Customer). When I add a record to the contacts table (/contacts/add), I can choose the customer (customer_id) from a select box containing all the customers in the database. How can I set it up so that I can choose the customer first (/customers/view/6), then add a contact for that specific customer (e.g. /contacts/add/6); and then remove the select box from the "add contact" form (maybe replacing it with a hidden customer_id field)?

+1  A: 

There are several ways to do this, but I think the best is using the named parameters.

Essentially, in your views/customers/view.ctp, you add a customer_id to the contacts/add link:

$html->link(__('Add contact', true), array('controller' => 'contacts', 'action' => 'add', 'customer_id' => $customer['Customer']['id']));

and in your views/contacts/add.ctp you check for the named parameter and use a hidden field:

if (isset($this->params['named']['customer_id'])) {
    echo $form->input('customer_id', array('type' => 'hidden', 'value' => $this->params['named']['customer_id']));
} else {
    echo $form->input('customer_id');
}

or a select with the right customer already selected:

echo $form->input('customer_id', array('selected' => @$this->params['named']['customer_id']));
Marko
That works exactly as I wanted - thank you. I don't need it for this application, but is there any reason to have the link pointing to e.g. /contacts/add/2 rather than /contacts/add/customer_id:2 (for seo, maybe)? And, if so, how might I go about setting this up?
Tomba
+1  A: 

However that is not a solution when you want to secure the field information. It still could be being received with a different value. How about a way to set it in the controller before saving??

Jma