日付範囲検索
少しハマったので整理しておく。
Modelに「created」日付があるとします。それを検索画面からfrom~toの範囲検索が必要な場合、
Searchプラグインを使っているならModelから簡単に設定で実装可能になる。
以下を参考にしてdatepickerを使って実装してみました。
参考:http://kamakurasoft.net/blog/?p=1479
datepickerダウンロード及び使い方はこちら
https://jqueryui.com/datepicker/
View
日付検索のコードだけを書きます。
datepicker関連jsやcssなどは上記のdatepickerサイト参照
<script type="text/javascript">
$(function(){
//こちらは自分にdatepicker設定。
$('#PostDateFrom').datepicker({'prevText':'<','nextText':'>'});
//カレンダから選択した日付をyyyy-mm-ddに表示
$('#PostDateFrom').datepicker("option", {
"dateFormat": "yy-mm-dd"
});
//検索後も日付を表示させるため
$('#PostDateFrom').val('<?= $date_from?>'); //コントローラから設定
$('#PostDateTo').datepicker({'prevText':'<','nextText':'>'});
$('#PostDateTo').datepicker("option", {
"dateFormat": "yy-mm-dd"
});
$('#InvoiceDateTo').val('<?= $date_to?>'); //コントローラから設定
});
</script>
<h2>検索</h2>
<?= $this->Form->input('date_from', ['type' => 'text']) ?>
<span> - </span>
<?= $this->Form->input('date_to' ,['type' => 'text']) ?>
Controller
<?php
class PostsController extends AppController{
public $uses = array('Post','Comment');
public $helpers = array('Html','Form');
public $components = array('Search.Prg');
public $presetVars = true;
public function index(){
$this->Prg->commonProcess();
$conditions = $this->Post->parseCriteria($this->passedArgs);
$this->paginate = array(
'limit'=>10,
//'order'=>array('id'=>'desc'),
'conditions'=>$conditions,
);
$this->set('posts',$this->paginate());
//postsにはfrom_date,to_dateがないため、こちらを追加してViewで表示
if (!empty($this->request->data['Post']['date_from'])) {
$this->set('date_from', $this->request->data['Post']['date_from']);
} else {
$this->set('date_from', '');
}
if (!empty($this->request->data['Post']['date_to'])) {
$this->set('date_to', $this->request->data['Post']['date_to']);
} else {
$this->set('date_to', '');
}
}
}
Model
Modelで追加が必要内容はfilterArgsに日付条件を追加する。
実際Postテーブルには「from_date」「to_date」が存在しないため、conditionsに実際テーブル名でconditionを追加する必要がある。
<?php
class Post extends AppModel{
....
public $actsAs = array('Search.Searchable');
public $filterArgs = array(
'date_from'=>array('type'=>'query','method'=>'_dateFromConditions'),
'date_to'=>array('type'=>'query','method'=>'_dateToConditions'),
);
//from_date
public function _dateFromConditions($data = array()){
$from_date = $data['from_date'];
$conditions = array('DATE(Post.created) >= DATE(?)'=>array($from_date));
return $conditions;
}
//to_date
public function _dateToConditions($data = array()){
$to_date = $data['to_date'];
$conditions = array('DATE(Post.created) <= DATE(?)'=>array($to_date));
return $conditions;
}
}
?>
これで完了です。
Serachプラグインについてはこちら参考
http://mawatari.jp/archives/introduction-of-cakedc-search-plugin-for-cakephp
その他CakePHP勉強を始める方は以下の情報もみてください。
http://qiita.com/amagasu1234/items/ba160f9e6264f7c90486