2010年4月26日月曜日

cakephp 1.2.6 で検索をバンドル

 ビュー index.ctp に対して

<div>
<form id="search-index" action="<?php echo $html->url('/users/index'); ?>" class='horz' method="get">
<?php
echo $form->input('Search', array('size'=>'30', 'value'=>$search_key, 'label'=>''));
echo $form->submit('検索');
?>
</div>
<p>
<?php
echo $paginator->counter(array(
'format' => __('Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%', true)
));
?></p>

という感じの検索フォームを追加。
 コントローラ側は、以下のような感じでインプリメント。

function index() {
$conditions = null;
if(isset($this->params['url']['data']['Search'])){
$key = $this->params['url']['data']['Search'];
$this->Session->write('user_cond',$key);
$conditions = $this->search_conditions( $key );
} else if( $this->Session->check('user_cond') ) {
$key = $this->Session->read('user_cond');
$conditions = $this->search_conditions( $key );
}
$this->User->recursive = 0;
$this->set('users', $this->paginate($conditions));
}

private function search_conditions( $param ) {
$this->set('search_key',$param);
$fields = array( 'User.name Like ?', 'User.account Like ?', 'User.ankname Like ?', 'Section.name Like ?' );
$result = array();
foreach( $fields as $f ) {
$result[$f] = '%' . $param . '%';
}
return array('or' => $result );
}

これならば、search_conditions 中の $fields を var $search_fields = array(...); と定義してやって、機械的に cake bake してもいいぐらい。ま、activescaffold に比べると、cakephp は見劣りしてしまうかな…。

参考:
CakePHPで検索機能の実装を少し楽する
条件をつけたpaginateでページ繰りができない

追記: $this->set('search_key',$foo); が行われない場合があるので、ビューの 'value'=>$search_key は、ちょっと buggy

0 件のコメント: