I have a classical index page with a form where I can filter my records.
One of my fields is year
. Let's say that I want the records to be pre-filtered by current year when the user first visit the page (ie when the query string is empty)
what have I done:
in my controller I did something like this
if(empty($this->request->query))
{
$this->request->query['year'] = date('Y');
}
and then with the help of friendsofcake/search plugig:
$this->MyTable->find('search', [
'search' => $this->request->getQuery()
]);
In this way the records are filtered and the form is pre compiled with the current year since in my view I have
'valueSources' => 'query'
Now with cake 3.6 direct modification of the query is deprecated (see this issue I opened). In fact I get deprecation warnings when I try to change the query array.
My question:
So I want to know what is the best way to achieve the same behavior without getting warnings. I would also like to know if and why my approach is wrong.
In controller:
$searchValues = $this->request->getQueryParams() ?: ['year' => date('Y')];
$this->MyTable->find('search', [
'search' => $searchValues
]);
$this->set(compact('searchValues'));
In template:
$this->Form->create(['schema' => [], 'defaults' => $searchValues]);
Ideally you would also set proper values in schema
as shown here https://api.cakephp.org/3.6/class-Cake.View.Form.ArrayContext.html
Try something like this (not tested):
$this->setRequest($this->getRequest()->withQueryParams([
'year' => date('Y'),
]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.