Title | Category | Year |
---|---|---|
The Godfather | movies | 1972 |
The Shawshank Redemption | movies | 1994 |
Schindler's List | movies | 1993 |
Raging Bull | movies | 1980 |
This tutorial explains the basic usage of paginators in Zend Framework 2.
It's based on the main object Zend\Paginator\Paginator
which wrapps an adapter, defining which page we want to handle and how many results to display.
In this case, since we are paginating a plain array of data, we have to use the Zend\Paginator\Adapter\ArrayAdapter
.
$paginator = new Paginator(new ArrayAdapter([
[
'title' => 'First element',
'category' => 'movies',
'year' => 1985
],
[
'title' => 'Second element',
'category' => 'books',
'year' => 1946
]
]));
$paginator->setCurrentPageNumber(2)
->setItemCountPerPage(4);
return new ViewModel(['paginator' => $paginator]);
After creating the paginator, we just need to pass it to the view template. It is an iterable object that only returns the elements in current page.
<table class="table">
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th class="text-right">Year</th>
</tr>
</thead>
<tbody>
<?php foreach ($this->paginator as $element): ?>
<tr>
<td><?php echo $element['title'] ?></td>
<td><?php echo $element['category'] ?></td>
<td class="text-right"><?php echo $element['year'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Finally we only need to display a pagination control. By using the paginationControl
view helper we can render it from a view partial.
echo $this->paginationControl(
$this->paginator,
'sliding',
'application/partials/paginator.phtml'
);
The view partial will get some params that will ease the creation of links to other pages, like current page number or previous and next pages. Also, next and previous page won't be set while we are in the first or last page.
echo $this->previous; // The previous page number. If not set, we are at the first page.
echo $this->next; // The next page number. If not set, we are at the last page.
echo $this->current; // Current page number.
foreach ($this->pagesInRange as $page) :
// The pagesInRange object containes the visible pages, which depends on the type of paginator (the second argument of the paginationControl helper)
endforeach;