我尝试使用CakeDc
插件在日期之间进行搜索。我试图在表单/视图中使用2个单独的表单字段,1表示开始日期,另一个表示结束日期。
我需要一个单独的数组,所以我可以在控制器中使用函数CreationDateRangeCondition
(除非这可以在控制器函数中以某种方式进行排序),但我不知道如何做到这一点。我正在尝试学习PHP
和Cakephp
控制器:
public $presetVars = array(
array('creationDateBetween' => 'created', 'type' => 'value'),
);
public function index() {
$this->Prg->commonProcess();
$this->paginate = array(
'conditions' => $this->Post->parseCriteria($this->passedArgs));
$this->set('posts', $this->paginate());
}
型号: public $ actsAs = array(' Search.Searchable');
public $filterArgs = array(
'creationDateBetween' => array(
'type' => 'expression',
'method' => 'CreationDateRangeCondition',
'field' => 'Post.created BETWEEN ? AND ?',
),
);
public function CreationDateRangeCondition($data = array()){
if(strpos($data['creationDateBetween'], ' - ') !== false){
$tmp = explode(' - ', $data['creationDateBetween']);
$tmp[0] = $tmp[0]."-01-01";
$tmp[1] = $tmp[1]."-12-31";
return $tmp;
}else{
return array($data['creationDateBetween']."-01-01", $data['creationDateBetween']."-12-31");
}
}
查看:
<?php
echo $this->Form->create('Post', array(
'url' => array_merge(array('action' => 'index'), $this->params['pass'])
));
echo $this->Form->input('creationDateBetween', array(
'type' => 'date',
'div' => false,
'dateFormat' => 'DMY',
'minYear' => 2013,
'maxYear' => date('Y'),
'style' => 'margin-right: 2px; margin-left: 2px',
'empty' => true,
'timeFormat' => null,
'selected' => array(
'day' => 1,
'month' => 1,
'year' => 2013
),
'empty' => false
));
echo $this->Form->input('creationDateBetween2', array(
'type' => 'date',
'div' => false,
'dateFormat' => 'DMY',
'minYear' => 2013,
'maxYear' => date('Y'),
'empty' => true,
'style' => 'margin-right: 2px; margin-left: 2px',
'timeFormat' => null,
'selected' => array(
'day' => date('D'),
'month' => date('M'),
'year' => date('Y')
),
'empty' => false
));
?>
<?php
echo $this->Form->submit(__('Search', true), array('div' => false));
echo $this->Form->end();
?>
答案 0 :(得分:0)
我会这样做:
在Model
public $filterArgs = array(
'creationDateBetween' => array(
'type' => 'expression',
'method' => 'formatStartDate',
'field' => 'Post.created >= ?'
),
'creationDateBetween2' => array(
'type' => 'expression',
'method' => 'formatEndDate',
'field' => 'Post.created <= ?'
)
);
public function formatStartDate($data = array())
{
$date = implode('-', array($data['creationDateBetween']['year'], $data['creationDateBetween']['month'], $data['creationDateBetween']['day']));
return array($date);
}
public function formatEndDate($data = array())
{
$date = implode('-', array($data['creationDateBetween2']['year'], $data['creationDateBetween2']['month'], $data['creationDateBetween2']['day']));
return array($date);
}