Cakephp pre-fill form by get method

I have a search form and I submit it using the GET method. After submitting the form, I need to pre-fill the form with the submitted values. If it is POST, then the cake will take care of it automatically, but it does not work for GET. I created form and form elements using the cakephp form helper. Is there an easy way to pre-populate fields rather than manually setting each field? Im using cakephp2.x

+4
source share
3 answers

I know this question was asked some time ago, but I had the same problem.

When you use GET, CakeRequest will not populate the CakeRequest::data property. The form helper typically uses this property to populate input values. Therefore, you must first populate this property with your GET data somewhere in your controller. For instance:

 $this->request->data = $this->request->query; 

Your next problem is that Form Helper ignores the model set for your form if you use GET. Unfortunately, this behavior is not documented, but this is mentioned:

You can also pass false for $model . This will put your form data in an array: $this->request->data (and not in the sub-array: $this->request->data['Model'] ). This can be convenient for short forms that may not represent anything in your database.

Therefore, when creating a search form, you will need to set the model to false . eg:

 echo $this->Form->create(false, array('type' => 'get')); 
+6
source

For CakePHP 3, you can simply create your form as follows:

 echo $this->Form->create($user); 

and in the controller action just set $ user as Entity

 $user = $this->Users->get($id); 
0
source

You can do this by filling out the $this->request->data property in your controller.

For example, let's say you have this as your form:

  <?= $this->Form->create('Search'); ?> <?= $this->Form->input('query'); ?> <?= $this->Form->end(); ?> 

Then in your controller action use:

  $this->request->data('Search.query', 'search data'); 
-1
source

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


All Articles