Search Bloguru posts

kiyokawa's Blog

https://en.bloguru.com/kiyokawa

freespace

CakePHP3: Two sets of pagination for the same model

thread
Say you want two sets of pagination against the same model, each with a different condition.

Here is how to do it, assuming we have a table called articles, and we want pagination for current articles and for past (expired) articles. In your controller, write this:


$this->paginate = [
'Articles' => [
'scope' => 'current_articles',
],
'PastArticles' => [
'scope' => 'past_articles',
],
];

TableRegistry::config('PastArticles', [
'className' => 'App\Model\Table\ArticlesTable',
'table' => 'articles',
'entityClass' => 'App\Model\Entity\Article',
]);

$currentArticles = $this->paginate(
$this->Articles->find('all', [
'scope' => 'current_articles'
])->where(['expiry >' => Time::now()])
);
$pastArticles = $this->paginate(
TableRegistry::getTableLocator()->get('PastArticles')->find('all', [
'scope' => 'past_articles'
])->where(['expiry <=' => Time::now()])
);

$this->set(compact('currentArticles','pastArticles'));


And in your view, do this:


$this->Paginator->options(['model' => 'Articles']);
echo $this->Paginator->first('<<');
echo $this->Paginator->prev('<');
echo $this->Paginator->numbers();
echo $this->Paginator->next('>');
echo $this->Paginator->last('>>');

$this->Paginator->options(['model' => 'PastArticles']);
echo $this->Paginator->first('<<');
echo $this->Paginator->prev('<');
echo $this->Paginator->numbers();
echo $this->Paginator->next('>');
echo $this->Paginator->last('>>');

#cakephp3

People Who Wowed This Post

  • If you are a bloguru member, please login.
    Login
  • If you are not a bloguru member, you may request a free account here:
    Request Account