Getting started with Paginator: a minimal example

in CakePHP


The built-in pagination changed in more recent CakePHP versions (4 and 5), it is now a view helper and no longer a controller component.

MVP

  1. In your Controller where you want to use pagination, load the helper:

    public function initialize(): void
    {
        parent::initialize();
        $this->viewBuilder()->addHelper('Paginator');
    }
  2. Paginate your query results before passing them to the view template:

    $query = $postsTable->find('all');
    $this->set([
        'posts' => $this->paginate($query),
    ]);
  3. In the view template where you want to display the pagination UI elements:

    Paginator->numbers() ?>
    
    Paginator->prev('« Previous') ?>
    Paginator->next('Next »') ?>
    
    Paginator->counter() ?>

That's it. The above should get you going.

Templates

Paginator templates determine which elements make up the final pagination UI. In particular, you can control what tags are used and what attributes they have.

  1. Create config/paginator-templates.php. If you're in a plugin, put it in the plugin's config folder. Doesn't have to be exactly paginator-templates, you can use any file name. Here's an example:

     '{{text}}',
    ];

    Each key in that array defines the template for the specific pagination element, such as link to the previous page, inactive link to the previous page etc. Here's the full list of these template configuration elements and their default values: CORE/src/View/Helper/PaginatorHelper.php:75.

  2. Change how you load the helper to your controller. Here make sure you use the right configuration file name.

    $this->viewBuilder()->addHelper('Paginator', [
        'templates' => 'paginator-templates'
    ]);

    If you're in a plugin:

    $this->viewBuilder()->addHelper('Paginator', [
        'templates' => $this->getPlugin().'.paginator-templates'
    ]);

Further reading: