我在CakePHP项目中有一个简单的搜索引擎。其中一个可搜索的字段设置如下(从我的视图):
echo $this->Form->input('field2', array('label' => 'FieldName', 'multiple' => true, 'div'=>false, 'class' => 'chosen', 'options' => $fromController));
用户可以从此下拉列表中选择多个条目,并返回选择。这很好用;但是,如果field2留空,我希望搜索根据field1中的值返回所有记录。有没有办法做到这一点?以下是返回搜索结果的Controller代码:
//Populate the dropdown
$fromController = $this->Model->find('list', array('fields' => array('field', 'field')));
$requirements = array();
$findOptions['conditions'] = array();
$findOptions['conditions'] = array_merge($findOptions['conditions'], array('Model.field1' => $this->request->data['Model']['field1'],
'Mode.field2' => $this->request->data['Model']['field2']));
$specificresults = $this->Model->searchOptions($findOptions);
$requirements = array_merge($specificresults);
来自Model的功能:
function searchOptions($findOptions = array()) {
$records = array();
$findOptions['order'] = array('Model.field1'=>'DESC');
// return the final result....
return $this->find('all', $findOptions);
}
现在,如果field1有一个值,但field2留空,则不返回任何内容。只需要弄清楚如何告诉控制器我想要一切。
答案 0 :(得分:1)
如果field2
条件为空,请取消设置: -
if (empty($this->request->data['Model']['field2'])) {
unset($findOptions['conditions']['Mode.field2'])
}