ページネーションのオプション設定を複数設定する。

通常だと、ページネーションのオプションは、以下のように1つだけしか書けない。

class NewsController extends AppController {

	public $paginate = [
       'limit' => 12,
       'order' => ['created' => 'desc'],
	];

}

しかしlimitを、indexアクションでは12にして、viewアクションでは1にしたかったので、以下のようにしてオプション設定を分けた。

model/table/NewsTable.php

class NewsTable extends Table {
・・・
   public function getOptions() {
       $option = array(
               'limit' => 1,
               'order' => array('id' => 'ASC')
       );
       return $option;
   }
}

NewsController.php

public function view() {

	/ Model/Table/NewsTableを読み込む。
	$this->loadModel("News");

	/ NewsTableに書いたページネーションのオプションを読み込む。
	$this->paginate = $this->News->getOptions();

	$news = $this->paginate($this->News);
	$this->set('news', $news);
	
}

NewsController.php

コード全体

<?php
namespace App\Controller;
class NewsController extends AppController
{
	public $helpers = [
       'Paginator' => ['templates' => 'paginatorTemplates']
	];
	
	public $paginate = [
       'limit' => 12,
       'order' => ['created' => 'desc'],
	];
	
	public function initialize()
	{
		parent::initialize();
		$this->loadModel("News");
	}
	/**
	 * 一覧.
	 */
	public function index()
	{
		// ページネーションを追加する。
		$news = $this->paginate($this->News);
		$this->set('news', $news);
	}
	/**
	 * 詳細.
	 */
	public function view()
	{
		// Model/Table/NewsTableを読み込む。
		$this->loadModel("News");
		// NewsTableに書いたページネーションのオプションを読み込む。
		// NewsのViewページでは、1記事ずつ表示させるので、limit=1に設定している。
		$this->paginate = $this->News->getOptions();
		$news = $this->paginate($this->News);
		$this->set('news', $news);
		
	}
}

参考サイト

https://teratail.com/questions/43693

この記事が気に入ったらサポートをしてみませんか?