Skip to content

PaginatorHelper

class PaginatorHelper(View $view, array $settings = array())

The Pagination helper is used to output pagination controls such as page numbers and next/previous links. It works in tandem with PaginatorComponent.

See also Pagination for information on how to create paginated datasets and do paginated queries.

method PaginatorHelper::sort($key, $title = null, $options = array())

Generates a sorting link. Sets named or querystring parameters for the sort and direction. Links will default to sorting by asc. After the first click, links generated with sort() will handle direction switching automatically. Link sorting default by 'asc'. If the resultset is sorted 'asc' by the specified key the returned link will sort by 'desc'.

Accepted keys for $options:

  • escape Whether you want the contents HTML entity encoded, defaults to true.

  • model The model to use, defaults to PaginatorHelper::defaultModel().

  • direction The default direction to use when this link isn't active.

  • lock Lock direction. Will only use the default direction then, defaults to false.

    Added in version 2.5

    You can now set the lock option to true in order to lock the sorting direction into the specified direction.

Assuming you are paginating some posts, and are on page one:

php
echo $this->Paginator->sort('user_id');

Output:

html
<a href="/posts/index/page:1/sort:user_id/direction:asc/">User Id</a>

You can use the title parameter to create custom text for your link:

php
echo $this->Paginator->sort('user_id', 'User account');

Output:

html
<a href="/posts/index/page:1/sort:user_id/direction:asc/">User account</a>

If you are using HTML like images in your links remember to set escaping off:

php
echo $this->Paginator->sort(
  'user_id',
  '<em>User account</em>',
  array('escape' => false)
);

Output:

html
<a href="/posts/index/page:1/sort:user_id/direction:asc/">
  <em>User account</em>
</a>

The direction option can be used to set the default direction for a link. Once a link is active, it will automatically switch directions like normal:

php
echo $this->Paginator->sort('user_id', null, array('direction' => 'desc'));

Output:

html
<a href="/posts/index/page:1/sort:user_id/direction:desc/">User Id</a>

The lock option can be used to lock sorting into the specified direction:

php
echo $this->Paginator->sort('user_id', null, array('direction' => 'asc', 'lock' => true));

method PaginatorHelper::sortDir(string $model = null, mixed $options = array())

method PaginatorHelper::sortKey(string $model = null, mixed $options = array())

method PaginatorHelper::numbers($options = array())

Returns a set of numbers for the paged result set. Uses a modulus to decide how many numbers to show on each side of the current page By default 8 links on either side of the current page will be created if those pages exist. Links will not be generated for pages that do not exist. The current page is also not a link.

Supported options are:

  • before Content to be inserted before the numbers.

  • after Content to be inserted after the numbers.

  • model Model to create numbers for, defaults to PaginatorHelper::defaultModel().

  • modulus how many numbers to include on either side of the current page, defaults to 8.

  • separator Separator content defaults to |

  • tag The tag to wrap links in, defaults to 'span'.

  • first Whether you want first links generated, set to an integer to define the number of 'first' links to generate. Defaults to false. If a string is set a link to the first page will be generated with the value as the title:

    php
    echo $this->Paginator->numbers(array('first' => 'First page'));
  • last Whether you want last links generated, set to an integer to define the number of 'last' links to generate. Defaults to false. Follows the same logic as the first option. There is a ~PaginatorHelper::last()` method to be used separately as well if you wish.

  • ellipsis Ellipsis content, defaults to '...'

  • class The class name used on the wrapping tag.

  • currentClass The class name to use on the current/active link. Defaults to current.

  • currentTag Tag to use for current page number, defaults to null. This allows you to generate for example Twitter Bootstrap like links with the current page number wrapped in extra 'a' or 'span' tag.

While this method allows a lot of customization for its output. It is also ok to just call the method without any params. :

php
echo $this->Paginator->numbers();

Using the first and last options you can create links to the beginning and end of the page set. The following would create a set of page links that include links to the first 2 and last 2 pages in the paged results:

php
echo $this->Paginator->numbers(array('first' => 2, 'last' => 2));

Added in version 2.1

The currentClass option was added in 2.1.

Added in version 2.3

The currentTag option was added in 2.3.

In addition to generating links that go directly to specific page numbers, you'll often want links that go to the previous and next links, first and last pages in the paged data set.

method PaginatorHelper::prev($title = '<< Previous', $options = array(), $disabledTitle = null, $disabledOptions = array())

Changed in version 2.3

For methods: PaginatorHelper::prev() and PaginatorHelper::next() it is now possible to set the tag option to false to disable the wrapper. New options disabledTag has been added.If you leave the $disabledOptions empty the $options parameter will be used. This can save some additional typing if both sets of options are the same.

method PaginatorHelper::next($title = 'Next >>', $options = array(), $disabledTitle = null, $disabledOptions = array())

method PaginatorHelper::first($first = '<< first', $options = array())

method PaginatorHelper::last($last = 'last >>', $options = array())

method PaginatorHelper::current(string $model = null)

method PaginatorHelper::hasNext(string $model = null)

method PaginatorHelper::hasPrev(string $model = null)

method PaginatorHelper::hasPage(string $model = null, integer $page = 1)

Creating a page counter

method PaginatorHelper::counter($options = array())

Returns a counter string for the paged result set. Using a provided format string and a number of options you can create localized and application specific indicators of where a user is in the paged data set.

There are a number of options for counter(). The supported ones are:

  • format Format of the counter. Supported formats are 'range', 'pages' and custom. Defaults to pages which would output like '1 of 10'. In the custom mode the supplied string is parsed and tokens are replaced with actual values. The available tokens are:

    • {:page} - the current page displayed.
    • {:pages} - total number of pages.
    • {:current} - current number of records being shown.
    • {:count} - the total number of records in the result set.
    • {:start} - number of the first record being displayed.
    • {:end} - number of the last record being displayed.
    • {:model} - The pluralized human form of the model name. If your model was 'RecipePage', {:model} would be 'recipe pages'. This option was added in 2.0.

    You could also supply only a string to the counter method using the tokens available. For example:

    php
    echo $this->Paginator->counter(
        'Page {:page} of {:pages}, showing {:current} records out of
         {:count} total, starting on record {:start}, ending on {:end}'
    );

    Setting 'format' to range would output like '1 - 3 of 13':

    php
    echo $this->Paginator->counter(array(
        'format' => 'range'
    ));
  • separator The separator between the actual page and the number of pages. Defaults to ' of '. This is used in conjunction with 'format' = 'pages' which is 'format' default value:

    php
    echo $this->Paginator->counter(array(
        'separator' => ' of a total of '
    ));
  • model The name of the model being paginated, defaults to PaginatorHelper::defaultModel(). This is used in conjunction with the custom string on 'format' option.

Modifying the options PaginatorHelper uses

method PaginatorHelper::options($options = array())

Sets all the options for the Paginator Helper. Supported options are:

  • url The URL of the paginating action. 'url' has a few sub options as well:

    • sort The key that the records are sorted by.
    • direction The direction of the sorting. Defaults to 'ASC'.
    • page The page number to display.

    The above mentioned options can be used to force particular pages/directions. You can also append additional URL content into all URLs generated in the helper:

    php
    $this->Paginator->options(array(
        'url' => array(
            'sort' => 'email', 'direction' => 'desc', 'page' => 6,
            'lang' => 'en'
        )
    ));

    The above adds the en route parameter to all links the helper will generate. It will also create links with specific sort, direction and page values. By default PaginatorHelper will merge in all of the current pass and named parameters. So you don't have to do that in each view file.

  • escape Defines if the title field for links should be HTML escaped. Defaults to true.

  • update The CSS selector of the element to update with the results of AJAX pagination calls. If not specified, regular links will be created:

    php
    $this->Paginator->options(array('update' => '#content'));

    This is useful when doing Ajax Pagination. Keep in mind that the value of update can be any valid CSS selector, but most often is simpler to use an id selector.

  • model The name of the model being paginated, defaults to PaginatorHelper::defaultModel().

Using GET parameters for pagination

Normally Pagination in CakePHP uses Named Parameters. There are times you want to use GET parameters instead. While the main configuration option for this feature is in PaginatorComponent, you have some additional control in the view. You can use options() to indicate that you want other named parameters to be converted:

php
$this->Paginator->options(array(
  'convertKeys' => array('your', 'keys', 'here')
));

Configuring the PaginatorHelper to use a JavaScript helper

By default the PaginatorHelper uses JsHelper to do AJAX features. However, if you don't want that and want to use a custom helper for AJAX links, you can do so by changing the $helpers array in your controller. After running paginate() do the following:

php
// In your controller action.
$this->set('posts', $this->paginate());
$this->helpers['Paginator'] = array('ajax' => 'CustomJs');

Will change the PaginatorHelper to use the CustomJs for AJAX operations. You could also set the 'ajax' key to be any helper, as long as that class implements a link() method that behaves like HtmlHelper::link()

Pagination in Views

It's up to you to decide how to show records to the user, but most often this will be done inside HTML tables. The examples below assume a tabular layout, but the PaginatorHelper available in views doesn't always need to be restricted as such.

See the details on PaginatorHelper in the API. As mentioned, the PaginatorHelper also offers sorting features which can be easily integrated into your table column headers:

php
// app/View/Posts/index.ctp
<table>
    <tr>
        <th><?php echo $this->Paginator->sort('id', 'ID'); ?></th>
        <th><?php echo $this->Paginator->sort('title', 'Title'); ?></th>
    </tr>
       <?php foreach ($data as $recipe): ?>
    <tr>
        <td><?php echo $recipe['Recipe']['id']; ?> </td>
        <td><?php echo h($recipe['Recipe']['title']); ?> </td>
    </tr>
    <?php endforeach; ?>
</table>

The links output from the sort() method of the PaginatorHelper allow users to click on table headers to toggle the sorting of the data by a given field.

It is also possible to sort a column based on associations:

html
<table>
    <tr>
        <th><?php echo $this->Paginator->sort('title', 'Title'); ?></th>
        <th><?php echo $this->Paginator->sort('Author.name', 'Author'); ?></th>
    </tr>
       <?php foreach ($data as $recipe): ?>
    <tr>
        <td><?php echo h($recipe['Recipe']['title']); ?> </td>
        <td><?php echo h($recipe['Author']['name']); ?> </td>
    </tr>
    <?php endforeach; ?>
</table>

The final ingredient to pagination display in views is the addition of page navigation, also supplied by the PaginationHelper:

php
// Shows the page numbers
echo $this->Paginator->numbers();

// Shows the next and previous links
echo $this->Paginator->prev(
  '« Previous',
  null,
  null,
  array('class' => 'disabled')
);
echo $this->Paginator->next(
  'Next »',
  null,
  null,
  array('class' => 'disabled')
);

// prints X of Y, where X is current page and Y is number of pages
echo $this->Paginator->counter();

The wording output by the counter() method can also be customized using special markers:

php
echo $this->Paginator->counter(array(
    'format' => 'Page {:page} of {:pages}, showing {:current} records out of
             {:count} total, starting on record {:start}, ending on {:end}'
));

Other Methods

method PaginatorHelper::link($title, $url = array(), $options = array())

method PaginatorHelper::url($options = array(), $asArray = false, $model = null)

method PaginatorHelper::defaultModel()

method PaginatorHelper::params(string $model = null)

method PaginatorHelper::param(string $key, string $model = null)

Added in version 2.4

The param() method was added in 2.4.

method PaginatorHelper::meta(array $options = array())

Added in version 2.6

The meta() method was added in 2.6.

Released under the MIT License.