【CakePHP】ページネーションを追加する
CakePHP3.8を使用。
ページネーションを追加する場合は、コントローラ、ビューに以下のコードを追加する。
■ページネーション追加コード
コントローラ
class PagesController extends AppController
{
/ limitで表示するレコードの数を指定する。
public $paginate = [
'limit' => 3
];
/ ページネーションのコンポーネントをロードする。
public function initialize() {
parent::initialize();
$this->loadComponent('Paginator');
}
/ アクションにページネーションを追加する。
public function index()
{
/ ページネーションを追加する。
$pages = $this->paginate($this->Pages);
$this->set(compact('pages'));
}
View
<div class="paginator">
<ul class="pagination">
<?= $this->Paginator->first('<< ' . __('first')) ?>
<?= $this->Paginator->prev('< ' . __('previous')) ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next(__('next') . ' >') ?>
<?= $this->Paginator->last(__('last') . ' >>') ?>
</ul>
<p>
<?= $this->Paginator->counter(['format' => __('Page {{page}} of {{pages}}, showing {{current}} record(s) out of {{count}} total')]) ?>
</p>
</div>
ページネーションを追加しない場合
ページネーションを追加しない場合は、コントローラのアクションに以下のようなコードを追加する。
コントローラ/アクション
public function index()
{
$pages = $this->set('pages', $this->Pages->find('all'));
}
あとからページネーションを追加する場合は、このコードを消して、
$this->set(compact('pages'));にするのを忘れないようにする。
■ページネーションのオプション
order データを昇順・降順で並べ替え
'order' => ['Users.created' => 'asc']
/ 'order' => ['カラム名' => 'asc or desc']
■ページネーションに検索フォームをつける
検索機能をつけるには、以下のようにコードを書く。
ContactController
public function find()
{
$contacts = [];
if ($this->request->is('post')) {
$find = $this->request->data['find'];
$contacts = $this->paginate($this->Contacts->find()
// 複数カラムをまたいで検索する場合は、orwhereでメソッドチェーンしていく。
->where(["body like " => '%' . $find . '%'])
->orwhere(["customer_name like " => '%' . $find . '%'])
->orwhere(["mail like " => '%' . $find . '%'])
);
}
$this->set('msg', null);
$this->set('contacts', $contacts);
}
find.ctp
<div>
<h3>お問い合わせ検索</h3>
<?= $msg ?>
<?= $this->Form->create() ?>
<fieldset>
<?= $this->Form->input('find'); ?>
<?= $this->Form->button('Submit') ?>
<?= $this->Form->end() ?>
</fieldset>
<table border="1">
<thead>
<tr>
<th>id</th>
<th>customer_name</th>
<th>mail</th>
<th>body</th>
<th>received</th>
<th>modified</th>
<th>username</th>
<th>flag</th>
</tr>
</thead>
<tbody>
<?php foreach ($contacts as $contact): ?>
<tr>
<td><?= h($contact->id) ?></td>
<td><?= h($contact->customer_name) ?></td>
<td><?= h($contact->mail) ?></td>
<td><?= h($contact->body) ?></td>
<td><?= h($contact->received) ?></td>
<td><?= h($contact->modified) ?></td>
<?php if(isset($contact->user->username)) : ?>
<td><?= h($contact->user->username) ?></td>
<?php else: ?>
<td></td>
<?php endif; ?>
<td><?= h($contact->flagLabel) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>