Tomba
Tomba

Reputation: 1743

cakephp adding record with some parameters fixed

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

Upvotes: 1

Views: 2910

Answers (3)

geo_t
geo_t

Reputation: 11

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.

Upvotes: 1

Jma
Jma

Reputation: 11

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

Upvotes: 1

Marko
Marko

Reputation: 3599

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']));

Upvotes: 5

Related Questions