我正在尝试在我的 cakephp 应用程序的结果页面上构建一个“搜索”框。该页面使用 cakePHP 分页组件来显示和“分页”结果。这很完美,但我很难让下一部分工作。
期望的结果:
- 一个带有输入框和几个选择框的 cakephp 表单(post),包括一个日期选择器,以便我可以在日期之间进行选择。用户应该能够填充这些字段并提交
- 提交时,用户选择应更改 Controller 中的 cakePHP 分页条件
- 在 View 中,我希望分页栏记录用户的选择,这样当我过滤不同的页面时,它会保持用户搜索。我知道这可以使用 $this->passedArgs 来实现,因此我使用 post 而不是 get。
代码:
// Form:
<?php
echo $this->Form->create('search', array('class' => false));
echo $this->Form->input('searchFor');
echo $this->Form->input('dateFrom');
echo $this->Form->input('dateTo');
echo $this->Form->end();
?>
// Controller:
if($this->request->is("post")) {
$filters = $this->request->data["search"];
$this->passedArgs["searchFor"] = $filters["searchFor"];
$this->passedArgs["dateFrom"] = $filters["dateFrom"]." 00:00:00";
$this->passedArgs["dateTo"] = $filters["dateTo"]." 00:00:00";
// Assign search parameters:
if($this->passedArgs["searchFor"] != "") {
$conditions["Model.field LIKE"] = "%".$this->passedArgs["searchFor"]."%";
}
$conditions["Model.created >="] = $this->passedArgs["dateFrom"];
$conditions["Model.created <="] = $this->passedArgs["dateTo"];
} else {
$conditions = array("Result.status_id >=" => 12);
}
$this->paginate = array(
'conditions' => $conditions,
'order' => array('Result.created ASC'),
'limit' => 20
);
$this->set("results",$this->paginate("Model");
// The view file:
<?php
$this->Paginator->options(array('url' => $this->passedArgs));
?>
我现在在哪里:
- 初始页面加载所有结果
- 当我填充搜索框时,它会返回我的结果
问题:
- 我确信我这样做的方式不正确,因为我现在需要进行 2 次检查,a) 检查结果是否已发布,b) 检查是否有可用的 passedArgs。我 100% 确信这不是正确的做法。
假设我有 2 个自由格式字段用于搜索,比如名字和姓氏,如果我将姓氏留空,我的 url 将如下所示,这看起来不正确。这意味着我必须分配默认值以确保下面的项目不会发生,这看起来不是很动态。
http://localhost/site/controller/action/surname:0/name:John/date:0/
- 刷新时它说该页面不存在,因为发布的值不再可用。
最佳答案
通常我在 Controller 中是这样进行的:
//transform POST into GET
if($this->request->is("post")) {
$url = array('action'=>'index');
$filters = array();
if(isset($this->data['searchFor']) && $this->data['searchFor']){
//maybe clean up user input here??? or urlencode??
$filters['searchFor'] = $this->data['searchFor'];
}
//redirect user to the index page including the selected filters
$this->redirect(array_merge($url,$filters));
}
$conditions = array();
//check filters on passedArgs
if(isset($this->passedArgs["searchFor"])){
$conditions["Model.field LIKE"] = "%".$this->passedArgs["searchFor"]."%";
}
//paginate as normal
$this->paginate = array(
'conditions' => $conditions,
'order' => array('Result.created ASC'),
'limit' => 20
);
想法是将表单发送的 POST 转换为 GET。所以你不会有分页器或刷新的问题
希望对你有帮助
关于php - cakePHP 分页和 passedArgs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10427510/