Paginating a custom find type

The recipe, Implementing a custom find type, showed us the power of extending the built-in model find types, including support to use the implemented custom types for fetching records or counting them.

Now that we know how to fetch and count custom find types, we can easily paginate a set of resulting rows. This recipe shows how to use CakePHP's built-in pagination support to paginate a set of rows that come as a result of a custom find type.

Getting ready

We need some sample models and data to work with, and we need the override of the find() method in AppModel to allow count operations on custom find types. Therefore, make sure you follow the entire recipe, Implementing a custom find type, including its Getting ready section.

How to do it...

  1. Create a file named posts_controller.php in your app/controllers folder. If you already have one, make sure its index() method is as follows:
    <?php
    class PostsController extends AppController {
    public function index() {
    $this->paginate['Post'] = array(
    'search',
    'fields' => array(
    'Post.id',
    'Post.title'
    ),
    'terms' => array(
    'Post 1',
    'Post 2'
    ),
    'limit' => 3
    );
    $posts = $this->paginate('Post'),
    $this->set(compact('posts'));
    }
    }
    ?>
    
  2. Create the view for the index action. If you don't have a folder named posts in your app/views folder, create it. Next, create a file named index.ctp in your app/views folder with the following contents:
    <p>
    <?php echo $this->Paginator->prev(); ?>
    &nbsp;
    <?php echo $this->Paginator->numbers(); ?>
    &nbsp;
    <?php echo $this->Paginator->next(); ?>
    </p>
    <ul>
    <?php foreach($posts as $post) { ?>
    <li>#<?php echo $post['Post']['id']; ?>: <?php echo $post['Post']['title']; ?></li>
    <?php } ?>
    </ul>
    
  3. If we now browse to http://localhost/posts, we see a paginated list of matching posts, showing the first three posts out of two pages, as shown in the following screenshot:
    How to do it...

How it works...

To paginate a custom find type, we need to specify the name of the find type as the value for index 0 of the pagination settings (or the first value if no index is defined). We can then pass any custom find settings as part of the pagination settings, as shown in the following code snippet:

$this->paginate['Post'] = array(
'search',
'terms' => array(
'Post 1',
'Post 2'
),
'limit' => 3
);

CakePHP's paginate() method will first issue a count (specifying the find type name in the type find setting) to get the total number of rows, and then a find operation using the custom find type to get the rows for the current page.

See also

  • Implementing AJAX based pagination
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.211.166