CakePHP 2.x Pagination Tutorial: Helper, Conditions, Limit, Sorting and More!

CakePHP Pagination is one of the fastest thing you can code with this amazing framework. In this post I’m gonna show you how you can create a pagination script in matter of few minutes, or even seconds! Cool? Let’s get started.

This post is part of my CakePHP tutorial series, before you proceed to this, make sure you already installed your CakePHP poperly, know the CakePHP classes and naming conventions, and much better if you can code the CakePHP CRUD operations.

Video Demo

Here’s a video demo of what will be our code ouput.

Controller Code

On our controller, we are going to have a query the cakePHP way, we are going to have the following conditions:

  • Won’t include the record with an ID of 6 (‘conditions’ => array(‘User.id !=’ => ’6′))
  • We will limit to 3 records per page (‘limit’ => 3)
  • Order the result by ID (‘order’ => array(‘id’ => ‘desc’)) in descending order

So here’s the code that will be added in our UsersController.php

public function view() {

    // we prepare our query, the cakephp way!
    $this->paginate = array(
        'conditions' => array('User.id !=' => '6'),
        'limit' => 3,
        'order' => array('id' => 'desc')
    );

    // we are using the 'User' model
    $users = $this->paginate('User');

    // pass the value to our view.ctp
    $this->set('users', $users);

}

The $users variable gives us an array that look like this:

cakephp-pagination

View Code

On our view.ctp, our data is presented with a table. The table header contains the paginator sort() method for sorting the data using any fields you want (and you won’t have to create another query!)

The $this->Paginator object (pagination helper) also has lots of methods for paging, please see the ‘pagination section’ on the code block below.

Also we used the <div class=’paging’> which uses the CakePHP generic CSS. You can change that if you want and be creative with your paging UI design.

<?php
// so we use the paginator object the shorter way.
// instead of using '$this->Paginator' everytime, we'll use '$paginator'
$paginator = $this->Paginator;

if($users){

    //creating our table
    echo "<table>";

        // our table header, we can sort the data user the paginator sort() method!
        echo "<tr>";

            // in the sort method, ther first parameter is the same as the column name in our table
            // the second parameter is the header label we want to display in the view
            echo "<th>" . $paginator->sort('id', 'ID') . "</th>";
            echo "<th>" . $paginator->sort('firstname', 'Firstname') . "</th>";
            echo "<th>" . $paginator->sort('lastname', 'Lastname') . "</th>";
            echo "<th>" . $paginator->sort('username', 'Username') . "</th>";
        echo "</tr>";

        // loop through the user's records
        foreach( $users as $user ){
            echo "<tr>";
                echo "<td>{$user['User']['id']}</td>";
                echo "<td>{$user['User']['firstname']}</td>";
                echo "<td>{$user['User']['lastname']}</td>";
                echo "<td>{$user['User']['username']}</td>";
            echo "</tr>";
        }

    echo "</table>";

    // pagination section
    echo "<div class='paging'>";

        // the 'first' page button
        echo $paginator->first("First");

        // 'prev' page button,
        // we can check using the paginator hasPrev() method if there's a previous page
        // save with the 'next' page button
        if($paginator->hasPrev()){
            echo $paginator->prev("Prev");
        }

        // the 'number' page buttons
        echo $paginator->numbers(array('modulus' => 2));

        // for the 'next' button
        if($paginator->hasNext()){
            echo $paginator->next("Next");
        }

        // the 'last' page button
        echo $paginator->last("Last");

    echo "</div>";

}

// tell the user there's no records found
else{
    echo "No users found.";
}
?>

Thanks for reading this tutorial code for pagination in CakePHP!


Comments

34 responses to “CakePHP 2.x Pagination Tutorial: Helper, Conditions, Limit, Sorting and More!”

  1. Nice tutorial. Simple and easy to follow.

    1. Thanks for dropping by and for the compliment @iprovidence! You can subscribe for more! 🙂

  2. Who still uses named params these days now anways? It’s query strings.

    1. Hi @6b6225db96d6fb4a34c6d50a9171d13f, would you tell us more about query strings?

  3. Cesar Augusto Vallenilla Avatar
    Cesar Augusto Vallenilla

    Thanks for this tutorial!

    1. You’re welcome @cesaraugustovallenilla, thanks for visiting 🙂

  4. wow great

    1. Thanks for dropping by @4cc4223a7ed1e809d3d2ba0eb90bab2f!

  5. Not Useful Avatar
    Not Useful

    This was so, but so not useful at all, thanks for nothing.

    1. Hi @8347e6e45a3516de65d25a03b793f5d9, can you tell us why this is not useful to you?

  6. Long Michael Avatar
    Long Michael

    I have three tables : ‘users’, ‘posts’ , ‘comment’

    one user has many posts, one post has many comment.

    I want to view one table (by html, and retreiving data from 3 table above)

    How to do it?
    Please help me.

      1. Hello @balckdrifter, thanks for sharing this resource to us!

  7. ninjazhai Avatar
    ninjazhai

    Hi @longmichael, I can’t visualize what you’re trying to do. Displaying all those data in one page is not recommended. You should find another way to do it.

  8. Chamandeep Singh Avatar
    Chamandeep Singh

    How to paginate with custom query in cakephp

  9. ninjazhai Avatar
    ninjazhai

    Hey, this tutorial is on my list but can’t publish it yet. but basically, the idea is to user ajax requests to reload the tabel with different set of data. you might want read this http://www.codeofaninja.com/2011/06/paginating-your-data-with-ajax-and.html

  10. Abhishek Avatar
    Abhishek

    Thanx dear it was awesome….

    1. ninjazhai Avatar
      ninjazhai

      You’re welcome Abhishek! Please share it to your friends!

  11. thanks for this great tutorial… i want to add datepicker in cakephp register form… pls help me

    1. ninjazhai Avatar
      ninjazhai

      Hi Rohan, how about using jQuery UI calendar picker for that? See our tutorial here: http://www.codeofaninja.com/2013/10/jquery-ui-tutorial-for-beginners.html

  12. Thx it’s help me

    1. ninjazhai Avatar
      ninjazhai

      You’re welcome @Ahhou!

  13. Just what I was looking for hours, thank you!

  14. ninjazhai Avatar
    ninjazhai

    Glad to be of help to you @julinestebanprezvalencia!

  15. Freddy Noriega Avatar
    Freddy Noriega

    Gracias.

    1. ninjazhai Avatar
      ninjazhai

      De nada Freddy!

  16. awesome. helped me a lot.

    1. ninjazhai Avatar
      ninjazhai

      Glad it helped @imran!

  17. pappu gotya Avatar
    pappu gotya

    Hey its working fine…just one problem..its creating extra pages than actual records…..my records are ending up to 16th page with limit=10 but it shows last page upto 124…why this is so…!!!
    Please reply me as soon as possible..

  18. Rijesh pp Avatar
    Rijesh pp

    i did not get it correctly .the data listed correctly but i did not get a view of links like previous,last like that.help me

  19. Catherine Calipay Avatar
    Catherine Calipay

    I don’t get the view of the links.. help

    1. Hello @catherinecalipay, what ‘view of the links’ are you referring to?

  20. Thank you so much dear. It’s really nice. I’m escaped from huge problem for using this code. Thank you man

    1. You’re welcome @disqus_RH7bS8jAnQ ! Glad we could help you. Please share our site to one of your friends if you have time. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *