Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is correct way to use Pagerfanta for pagination in Symfony2

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);
    $pager->setMaxPerPage(10);
    if (!$page)    $page = 1;
    try  {
        $pager->setCurrentPage($page);
    }
    catch(NotValidCurrentPageException $e) {
      throw new NotFoundHttpException('Illegal page');
    }
    return $this->render('MyBundle:MyEntity:index.html.twig', array(
        'pager' => $pager,
    ));
}

In my template:

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

{% 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.

like image 566
j_goldman Avatar asked Sep 10 '12 13:09

j_goldman


1 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:

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

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

Worked for me.

like image 137
singingstars Avatar answered Sep 28 '22 09:09

singingstars