Paginator

Need to page a data listing? Because mathematics behind pagination can be tricky, Nette\Utils\Paginator will help you.

Installation:

composer require nette/utils

Lets create a paging object and set basic information for it:

$paginator = new Nette\Utils\Paginator;
$paginator->setPage(1); // the number of the current page (numbered from 1)
$paginator->setItemsPerPage(30); // the number of records per page
$paginator->setItemCount(356); // the total number of records (if available)

Pages are numbered from 1. We can change it using setBase():

$paginator->setBase(0); // numbered from 0

The object will now provide all the basic information useful in creating a paginator. You can, for example, pass it to a template and use it there.

$paginator->isFirst() // is this the first page?
$paginator->isLast() // is this the last page?
$paginator->getPage(); // current page number
$paginator->getFirstPage(); // the first page number
$paginator->getLastPage(); // the last page number
$paginator->getPageIndex(); // current page number if numbered form 0
$paginator->getItemsPerPage(); // the number of records per page
$paginator->getItemsCount(); // the total number of records (if available)

The paginator will help in formulating the SQL query. The getLength() and getOffset() methods return the values you may use in the LIMIT and OFFSET clauses:

$result = $database->query(
	'SELECT * FROM items LIMIT ? OFFSET ?',
	$paginator->getLength(),
	$paginator->getOffset()
);

If you need to paginate in reverse order, i.e. page no. 1 corresponds to the highest offset, you may use getCountdownOffset():

$result = $database->query(
	'SELECT * FROM items LIMIT ? OFFSET ?',
	$paginator->getLength(),
	$paginator->getCountdownOffset()
);

An example of use in the application can be found in the cookbook Paginating Database Results.

Improve this page