Does anyone know how to implement Ajax Pagination with Zend Framework 3 (zf3)?
I used Doctrine ORM to retrieve data from database.
Sure. The same as a normal GET request really, only will you respond dynamically because it concerns an xml http request
.
Take, for example, the following indexAction
use Zend\View\Model\JsonModel;
// class, other use-statements, etc
public function indexAction()
{
$page = $this->params()->fromQuery('page', 1); // get page from GET, default page 1
/** @var QueryBuilder $qb */
$qb = $this->getObjectManager()->createQueryBuilder();
$qb->select('u')
->from(User::class, 'u')
->orderBy('u.createdAt', 'DESC');
$paginator = new Paginator(new OrmAdapter(new OrmPaginator($qb)));
$paginator->setCurrentPageNumber($page);
$paginator->setItemCountPerPage(25);
if ($this->getRequest()->isXmlHttpRequest()) {
return new JsonModel([
'paginator' => $paginator,
'queryParams' => $this->params()->fromQuery(),
]);
}
return [
'paginator' => $paginator,
'queryParams' => $this->params()->fromQuery(),
];
}
Here you would normally end up at the bottom most return
statement for a standard GET request. In case of an ajax type request, the statement $this->getRequest()->isXmlHttpRequest()
returns true
and you know it's something send via, let's say $.ajax / $.get / $.post
(usually, unless native JS or something similar). In these cases you want to respond with just the data, not a completely rendered views. This is when you return the JsonModel
.
To make sure it works as intended, you must also have the JsonViewStrategy
enabled in your configuration. You might wish to enable this in your global.php
instead of just a module, like below, to enable it everywhere:
'view_manager' => [
//...
'strategies' => [
'ViewJsonStrategy',
],
],
The only things left to do, then, are client-side things with JavaScript. Like making sure you update the pagination, page contents, etc. Maybe a URI anchor...