【问题标题】:Ho to set a default query parameter in cakephp 3.6?如何在 cakephp 3.6 中设置默认查询参数?
【发布时间】:2018-04-20 06:36:00
【问题描述】:

我有一个经典的索引页面,其中包含一个可以过滤我的记录的表单。

我的一个字段是year。假设我希望在用户首次访问页面时(即查询字符串为空时)按当前年份预过滤记录

我做了什么:

在我的控制器中我做了这样的事情

if(empty($this->request->query))
{
    $this->request->query['year'] =  date('Y');
}

然后在friendsofcake/search插件的帮助下:

$this->MyTable->find('search', [
    'search' => $this->request->getQuery()
]);

以这种方式过滤记录,并且表单与当前年份一起预编译,因为在我看来,我有

'valueSources' => 'query'

现在不推荐使用 cake 3.6 直接修改查询(请参阅 this 我打开的问题)。事实上,当我尝试更改查询数组时,我会收到弃用警告。

我的问题:

所以我想知道在不收到警告的情况下实现相同行为的最佳方法是什么。我也想知道我的方法是否以及为什么是错误的。

【问题讨论】:

    标签: php cakephp cakephp-3.0


    【解决方案1】:

    在控制器中:

    $searchValues = $this->request->getQueryParams() ?: ['year' => date('Y')];
    $this->MyTable->find('search', [
        'search' => $searchValues
    ]);
    $this->set(compact('searchValues'));
    

    在模板中:

    $this->Form->create(['schema' => [], 'defaults' => $searchValues]);
    

    理想情况下,您还可以在schema 中设置正确的值,如此处所示https://api.cakephp.org/3.6/class-Cake.View.Form.ArrayContext.html

    【讨论】:

    • 感谢您的回答。如何告诉表单使用 MyTable 架构?
    【解决方案2】:

    尝试这样的事情(未测试):

    $this->setRequest($this->getRequest()->withQueryParams([
        'year' => date('Y'),
    ]);
    

    【讨论】:

    • 这将重置整个查询字符串。但当然,您可以将合并的数组传递给相同的方法,并且它可以工作。但我更想知道是否有更好的方法
    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    相关资源
    最近更新 更多