我有一个搜索表单,其中包含一个文本输入框,三个复选框以及一个基于数据库中用户数据的下拉列表中的预选默认值。 例如如果用户居住在公社1中,则在下拉列表中选择1作为默认值。
我希望CakePHP在由该值过滤的数据库中执行搜索,并返回分页结果。按下提交按钮时这很容易,但我想在没有用户交互的情况下在页面加载时执行搜索。
现在,在控制器中,我试图从下拉列表获取公共值,而不是下拉列表:
if ($this->request->is('post)) {
//Perform normal search with the other input fields included.
} else {
//Do the filtered search only by commune value, which I get from a function.
}
问题是,那么分页将不起作用。这是预期的,因为分页使用GET。当我尝试更改页面时,它不是一个帖子,并且搜索条件将再次设置为仅为commune值的值,并且我在SQL语句中出现错误。
如果我上面的解释有点乱,我很抱歉,但你不得不原谅我,因为英语不是我的第一语言。
我需要有关如何以另一种方式执行此操作的建议。它可能吗?我怀疑有一个简单的解决方案,但我是CakePHP的新手,似乎无法得到它。
$conditions = $this->setSearchConditions($this->request->data);
$res = $this->paginate('Ad', array($conditions));
$this->set('res', $res);
//limit is set in public $paginate variable
private function setSearchConditions($data) {
$conditions = array();
// $this->log('Search: DATA', 'debug');
//$this->log($data, 'debug');
if ($this->request->is('post)) { //Submit-button is clicked, performing full search
//$this->log('Dette er en post', 'debug');
if ($data['Ad']['searchField']) { //Text searchfield is not empty, adding title or description to search criteria
$this->log('Søkefeltet er ikke tomt', 'debug');
$str_search = '%' . $data['Ad']['searchField'] . '%';
$conditions[] = array(
'OR' => array(
'Ad.title LIKE' => $str_search,
'Ad.description LIKE' => $str_search
)
);
}//if
if ($data['Ad']['commune_id']) { // Commune dropdown is not empty, adding commune_id to search criteria
$conditions[] = array(
'Ad.commune_id' => $data['Ad']['commune_id']
);
}//if
if ($data['Ad']['type_id']) { // Type checkboxes are not empty, adding type_id to search criteria
$orArray = array();
foreach ($data['Ad']['type_id'] as $type) {
$orArray[] = array('Ad.type_id' => $type);
}
$conditions[] = array(
'OR' => $orArray
);
}//if
} else {
$conditions[] = array(
'Ad.commune_id' => $this->getDefaultCommune();
):
}
return $conditions;
}
答案 0 :(得分:1)
我尝试了CakeDC搜索插件(请参阅初始问题中Marks评论的答案。)并通过电子邮件向他们发送了类似的问题。解决方案是使用默认搜索条件设置数组,并将其与搜索条件合并。这是控制器代码:
public function view() {
$this->set('title_for_layout', 'Localtrade Norway');
$this->set('show_searchbar', true); //Shows searchbar div in view
$this->log($this->request->data, 'debug');
//Setting users home commune as default filter when the form is not submitted.
$default_filter = array(
'Ad.commune_id' => $this->Auth->user('User.commune_id')
);
$this->Prg->commonProcess(); //Search-plugin
$this->paginate = array(
'conditions' => array_merge($default_filter, $this->Ad->parseCriteria($this->passedArgs)), //If Ad.commune_id is empty in second array, then the first will be used.
'fields' => $this->Ad->setFields(),
'limit' => 3
);
$this->set('res', $this->paginate());
}