Pagination

  • class Cake\Controller\Component\PaginatorComponent
  • One of the main obstacles of creating flexible and user-friendly webapplications is designing an intuitive user interface. Many applications tend togrow in size and complexity quickly, and designers and programmers alike findthey are unable to cope with displaying hundreds or thousands of records.Refactoring takes time, and performance and user satisfaction can suffer.

Displaying a reasonable number of records per page has always been a criticalpart of every application and used to cause many headaches for developers.CakePHP eases the burden on the developer by providing a quick, easy way topaginate data.

Pagination in CakePHP is offered by a component in the controller, to makebuilding paginated queries easier. In the ViewView\Helper\PaginatorHelper is used to make the generationof pagination links & buttons simple.

Using Controller::paginate()

In the controller, we start by defining the default query conditions paginationwill use in the $paginate controller variable. These conditions, serve asthe basis for your pagination queries. They are augmented by the sort, direction,limit, and page parameters passed in from the URL. It is important to notethat the order key must be defined in an array structure like below:

  1. class ArticlesController extends AppController
  2. {
  3. public $paginate = [
  4. 'limit' => 25,
  5. 'order' => [
  6. 'Articles.title' => 'asc'
  7. ]
  8. ];
  9.  
  10. public function initialize()
  11. {
  12. parent::initialize();
  13. $this->loadComponent('Paginator');
  14. }
  15. }

You can also include any of the options supported byORM\Table::find(), such as fields:

  1. class ArticlesController extends AppController
  2. {
  3. public $paginate = [
  4. 'fields' => ['Articles.id', 'Articles.created'],
  5. 'limit' => 25,
  6. 'order' => [
  7. 'Articles.title' => 'asc'
  8. ]
  9. ];
  10.  
  11. public function initialize()
  12. {
  13. parent::initialize();
  14. $this->loadComponent('Paginator');
  15. }
  16. }

While you can pass most of the query options from the paginate property it isoften cleaner and simpler to bundle up your pagination options intoa Custom Finder Methods. You can define the finder pagination uses bysetting the finder option:

  1. class ArticlesController extends AppController
  2. {
  3. public $paginate = [
  4. 'finder' => 'published',
  5. ];
  6. }

Because custom finder methods can also take in options, this is how you pass inoptions into a custom finder method within the paginate property:

  1. class ArticlesController extends AppController
  2. {
  3. // find articles by tag
  4. public function tags()
  5. {
  6. $tags = $this->request->getParam('pass');
  7.  
  8. $customFinderOptions = [
  9. 'tags' => $tags
  10. ];
  11. // the custom finder method is called findTagged inside ArticlesTable.php
  12. // it should look like this:
  13. // public function findTagged(Query $query, array $options) {
  14. // hence you use tagged as the key
  15. $this->paginate = [
  16. 'finder' => [
  17. 'tagged' => $customFinderOptions
  18. ]
  19. ];
  20. $articles = $this->paginate($this->Articles);
  21. $this->set(compact('articles', 'tags'));
  22. }
  23. }

In addition to defining general pagination values, you can define more than oneset of pagination defaults in the controller, you just name the keys of thearray after the model you wish to configure:

  1. class ArticlesController extends AppController
  2. {
  3. public $paginate = [
  4. 'Articles' => [],
  5. 'Authors' => [],
  6. ];
  7. }

The values of the Articles and Authors keys could contain all the propertiesthat a model/key less $paginate array could.

Once the $paginate property has been defined, we can use theController\Controller::paginate() method to create thepagination data, and add the PaginatorHelper if it hasn’t already beenadded. The controller’s paginate method will return the result set of thepaginated query, and set pagination metadata to the request. You can access thepagination metadata at $this->request->getParam('paging'). A more completeexample of using paginate() would be:

  1. class ArticlesController extends AppController
  2. {
  3. public function index()
  4. {
  5. $this->set('articles', $this->paginate());
  6. }
  7. }

By default the paginate() method will use the default model fora controller. You can also pass the resulting query of a find method:

  1. public function index()
  2. {
  3. $query = $this->Articles->find('popular')->where(['author_id' => 1]);
  4. $this->set('articles', $this->paginate($query));
  5. }

If you want to paginate a different model you can provide a query for it, thetable object itself, or its name:

  1. // Using a query
  2. $comments = $this->paginate($commentsTable->find());
  3.  
  4. // Using the model name.
  5. $comments = $this->paginate('Comments');
  6.  
  7. // Using a table object.
  8. $comments = $this->paginate($commentTable);

Using the Paginator Directly

If you need to paginate data from another component you may want to use thePaginatorComponent directly. It features a similar API to the controllermethod:

  1. $articles = $this->Paginator->paginate($articleTable->find(), $config);
  2.  
  3. // Or
  4. $articles = $this->Paginator->paginate($articleTable, $config);

The first parameter should be the query object from a find on table object youwish to paginate results from. Optionally, you can pass the table object and letthe query be constructed for you. The second parameter should be the array ofsettings to use for pagination. This array should have the same structure as the$paginate property on a controller. When paginating a Query object, thefinder option will be ignored. It is assumed that you are passing inthe query you want paginated.

Paginating Multiple Queries

You can paginate multiple models in a single controller action, using thescope option both in the controller’s $paginate property and in thecall to the paginate() method:

  1. // Paginate property
  2. public $paginate = [
  3. 'Articles' => ['scope' => 'article'],
  4. 'Tags' => ['scope' => 'tag']
  5. ];
  6.  
  7. // In a controller action
  8. $articles = $this->paginate($this->Articles, ['scope' => 'article']);
  9. $tags = $this->paginate($this->Tags, ['scope' => 'tag']);
  10. $this->set(compact('articles', 'tags'));

The scope option will result in PaginatorComponent looking inscoped query string parameters. For example, the following URL could be used topaginate both tags and articles at the same time:

  1. /dashboard?article[page]=1&tag[page]=3

See the Paginating Multiple Results section for how to generate scoped HTMLelements and URLs for pagination.

New in version 3.3.0: Multiple Pagination was added in 3.3.0

Paginating the Same Model multiple Times

To paginate the same model multiple times within a single controller action youneed to define an alias for the model. See Using the TableRegistry foradditional details on how to use the table registry:

  1. // In a controller action
  2. $this->paginate = [
  3. 'ArticlesTable' => [
  4. 'scope' => 'published_articles',
  5. 'limit' => 10,
  6. 'order' => [
  7. 'id' => 'desc',
  8. ],
  9. ],
  10. 'UnpublishedArticlesTable' => [
  11. 'scope' => 'unpublished_articles',
  12. 'limit' => 10,
  13. 'order' => [
  14. 'id' => 'desc',
  15. ],
  16. ],
  17. ];
  18.  
  19. // Register an additional table object to allow differentiating in pagination component
  20. TableRegistry::config('UnpublishedArticles', [
  21. 'className' => 'App\Model\Table\ArticlesTable',
  22. 'table' => 'articles',
  23. 'entityClass' => 'App\Model\Entity\Article',
  24. ]);
  25.  
  26. $publishedArticles = $this->paginate(
  27. $this->Articles->find('all', [
  28. 'scope' => 'published_articles'
  29. ])->where(['published' => true])
  30. );
  31.  
  32. $unpublishedArticles = $this->paginate(
  33. TableRegistry::getTableLocator()->get('UnpublishedArticles')->find('all', [
  34. 'scope' => 'unpublished_articles'
  35. ])->where(['published' => false])
  36. );

Control which Fields Used for Ordering

By default sorting can be done on any non-virtual column a table has. This issometimes undesirable as it allows users to sort on un-indexed columns that canbe expensive to order by. You can set the whitelist of fields that can be sortedusing the sortWhitelist option. This option is required when you want tosort on any associated data, or computed fields that may be part of yourpagination query:

  1. public $paginate = [
  2. 'sortWhitelist' => [
  3. 'id', 'title', 'Users.username', 'created'
  4. ]
  5. ];

Any requests that attempt to sort on fields not in the whitelist will beignored.

Limit the Maximum Number of Rows per Page

The number of results that are fetched per page is exposed to the user as thelimit parameter. It is generally undesirable to allow users to fetch allrows in a paginated set. The maxLimit option asserts that no one can setthis limit too high from the outside. By default CakePHP limits the maximumnumber of rows that can be fetched to 100. If this default is not appropriatefor your application, you can adjust it as part of the pagination options, forexample reducing it to 10:

  1. public $paginate = [
  2. // Other keys here.
  3. 'maxLimit' => 10
  4. ];

If the request’s limit param is greater than this value, it will be reduced tothe maxLimit value.

Joining Additional Associations

Additional associations can be loaded to the paginated table by using thecontain parameter:

  1. public function index()
  2. {
  3. $this->paginate = [
  4. 'contain' => ['Authors', 'Comments']
  5. ];
  6.  
  7. $this->set('articles', $this->paginate($this->Articles));
  8. }

Out of Range Page Requests

The PaginatorComponent will throw a NotFoundException when trying toaccess a non-existent page, i.e. page number requested is greater than totalpage count.

So you could either let the normal error page be rendered or use a try catchblock and take appropriate action when a NotFoundException is caught:

  1. // Prior to 3.6 use Cake\Network\Exception\NotFoundException
  2. use Cake\Http\Exception\NotFoundException;
  3.  
  4. public function index()
  5. {
  6. try {
  7. $this->paginate();
  8. } catch (NotFoundException $e) {
  9. // Do something here like redirecting to first or last page.
  10. // $this->request->getParam('paging') will give you required info.
  11. }
  12. }

Pagination in the View

Check the View\Helper\PaginatorHelper documentation forhow to create links for pagination navigation.