cakePHP3で、ページング時に検索条件を引き継ぐためのコンポーネントです。 元々cakephpのページング時の検索条件の引き継ぎで公開されているコードを、CakePHP3でも動作するように カスタマイズしました。
CakePHP3フレームワークのプロジェクトのsrc/Controller/Component
フォルダ内にdist/PagingSupportComponent.php
ファイルを設置します。
以下のように関連ファイルに追記します。
コンポーネントのインポート
public function initialize()
{
parent::initialize();
//PagingSupport の追加
$this->loadComponent('PagingSupport');
//
}
コントローラー内で呼び出し
public function index()
{
//コンポーネントを呼び出す文を追加
$this->PagingSupport->inheritPostData();
//
if(!empty($this->request->data)){
//検索条件処理等...
}
$users = $this->paginate($query);
$this->set(compact('users'));
}
$paginate
コントローラー変数にparamType
を追加
$this->paginate = [
//paramTypeをquerystringに設定
'paramType' => 'querystring'
//
];
ビューの中でPaginator
のオプションにusePaging
パラメータを追加
<ul class="pagination">
<?php
//optionsのurlにusePagingパラメータを追加
$this->Paginator->options(['url'=> ['action'=>'index','usePaging'=>1]]);
//
?>
<?= $this->Paginator->first('<< ' . __('最初')) ?>
<?= $this->Paginator->prev('< ' . __('前')) ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next(__('次') . ' >') ?>
<?= $this->Paginator->last(__('最後') . ' >>') ?>
</ul>
- 検索時に検索条件のリクエストデータをセッションに保存
- ページング利用時にセッションから検索条件を読み取りリクエストデータに保存
- 上記以外にセッションデータを削除
上記2番目のページング利用の判断に使いますが、コンポーネント内では、リクエストパラムの"?"キー内に
あるので、request->params['?']['usePaging']
でアクセスしています。