【CakePHP】Pagination(ページネーション)を使用する:基本
バージョン:CakePHP 2.x
CakePHPで検索結果をページングやソートする処理を行う場合には、Pagination機能を使用すると楽に実装できます。
1.コントローラにページネーションの設定を追加する
コントローラに1ページに表示する件数や、データの順序などを設定します。
1 2 3 4 5 6 | public $paginate = array ( 'モデル名' => array ( 'limit' =>10, //1ページ表示できるデータ数の設定 'order' => array ( 'id' => 'asc' ), //データを降順に並べる ) ); |
2.ビューにデータを受け渡す
$this->paginate()でViewにセットします。
1 | $this ->set( 'モデル名' , $this ->paginate()); |
3.ビューの表示
prevで前の画面へのリンク、nextで次の画面へのリンクを設定します。
numbersはページ番号が表示されます。
1 2 3 4 5 6 7 8 9 | echo $this ->Paginator->prev( '< 前へ' , array (), null, array ( 'class' => 'prev disabled' )); echo $this ->Paginator->numbers( array ( 'separator' => '' )); echo $this ->Paginator->next( '次へ >' , array (), null, array ( 'class' => 'next disabled' )); <?php foreach ( $Users as $row ): ?> //データの表示 <?php echo $row [ 'row' ][ 'id' ]; ?> <?php echo $row [ 'row' ][ 'last_name' ]; ?> <?php echo $row [ 'row' ][ 'first_name' ]; ?> <?php endforeach ; ?> |
こんな感じで簡単にページング処理が可能です。
▽まとめ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php class TestController extends AppController { public $uses = array ( 'Users' ); //Paginationの設定 public $paginate = array ( 'Users' => array ( 'limit' =>10, //1ページ表示できるデータ数の設定 'order' => array ( 'id' => 'asc' ), //データを降順に並べる ) ); function beforeFilter(){ parent::beforeFilter(); } function index(){ //データをPaginatorへセット $this ->set( 'Users' , $this ->paginate()); } } |