Home » Php » php – What is correct way to use Pagerfanta for pagination in Symfony2

php – What is correct way to use Pagerfanta for pagination in Symfony2

Posted by: admin July 12, 2020 Leave a comment


I have read that Pagerfanta is the pagination plugin of choice for Symfony2, but I am having some trouble getting it to work correctly. I have downloaded the code for pagerfanta and PagerfantaBundle and installed them as described in the WhiteOctober Github readme file and in this tutorial. I’m pretty sure the code in my controller is okay, but there is something wrong with my template file.

My controller code:

public function indexAction($page =  null)
    $query = $em->createQuery('SELECT something FROM some_table');
    $adapter = new DoctrineORMAdapter($query);
    $pager =  new Pagerfanta($adapter);
    if (!$page)    $page = 1;
    try  {
    catch(NotValidCurrentPageException $e) {
      throw new NotFoundHttpException('Illegal page');
    return $this->render('MyBundle:MyEntity:index.html.twig', array(
        'pager' => $pager,

In my template:

  {% for object in pager.currentPageResults %}
      <td>{{ object.attribute1 }}</td>
      <td>{{ object.attribute2 }}</td>
      <td>{{ object.attribute3 }}</td>
  {% endfor %}

{% if pager.haveToPaginate %}
  {{ pagerfanta(pager) }}
{% endif %}

When I go to the page, I get a list of the first 10 objects. However,the rendering of the pager is just PreviousNext as one word (not links and no pages 1, 2, 3, etc).

If I add ?page=2 to the URL, it doesn’t display the next 10 items in the list.

I didn’t change the route from what is was before I added the pagination code because the documentation says:

The routes are generated automatically for the current route using the variable “page” to propagate the page number.

… but I wonder if incorrect routing is part of the problem. Assuming this is the case, I’m not sure how to proceed with this.

I have been unable to find any instructions other the sources I have linked to above, so it would be great if someone who has implemented this successfully could share the details of how they did it.

How to&Answers:

I think your application doesn’t know how to parse ?page=2 to the controller action.

Include a {page} in your route (as @AdrienBrault replied), which you wish to have pagination.

like this:

  pattern:  /{page}
  defaults: { _controller: MyTestBundle:Object:index, page: 1 }
    _method:  GET
    page: \d+

PagerFantaBundle will (I guess) try to guess the correct route.

Worked for me.


I had to use ‘currenPage’ instead fo ‘page’ in my routing and I found a way to do this :

{{ pagerfanta(pager, 'my_pager_view', {'pageParameter':'[currentPage]'}) }}