简体   繁体   English

如何在cakephp 3.6中设置默认查询参数?

[英]Ho to set a default query parameter in cakephp 3.6?

I have a classical index page with a form where I can filter my records. 我有一个经典的索引页,其中包含可以过滤记录的表单。

One of my fields is year . 我的领域之一是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: 然后在friendsofcake /搜索插件的帮助下:

$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). 现在蛋糕3.6查询的直接修改已被弃用(见这个问题,我打开)。 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 理想情况下,您还可以在schema设置适当的值,如下所示: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'),
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM