Cakephp adds a record with fixed parameters

I am sure that such a problem should be common in cakephp (which I recently started using), but I could not find a clear answer.

In my database, I have, among other things, tables called clients and contacts, in a one-to-many relationship (the client has a small contact, the contact belongs to the client). When I add an entry to the contacts table (/ contacts / add), I can select the customer (customer_id) from the selection field that contains all the customers in the database. How can I configure it to select a customer first (/ customers / view / 6) and then add a contact for that specific customer (for example, / contacts / add / 6); and then remove the selection field from the "add contact" form (possibly replacing it with a hidden customer_id field)?

+1
source share
3 answers

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

Essentially, in your views /clients/view.ctp, you add client_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 the named parameter and use the 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 select the desired client that is already selected:

 echo $form->input('customer_id', array('selected' => @$this->params['named']['customer_id'])); 
+5
source

However, this is not a solution if you want to protect field information. It could still be obtained with a different value. How about a way to install it in the controller before saving?

+1
source

To answer the security problem with hidden fields, you can use the cake protection component, which blocks them to prevent unauthorized access. It works simply by adding it out of the box.

+1
source

Source: https://habr.com/ru/post/1304582/


All Articles