1

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)?

3 Answers 3

5

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']));
Sign up to request clarification or add additional context in comments.

2 Comments

Neat way of getting rid of unset array key :)
Finally found an answer! =DDD Great job!
1

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??

Comments

1

To answer the security problem with using hidden fields, you can use cake's Security component which locks them to prevent tampering. It works simply by adding it out of the box.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.