How to use Pagerfanta with Symfony2 and Doctrine2

Posted November 27th, 2011 in Tehnikalije by Metod

So let’s assume you want to use a pager with your Symfony2 application. If you are like me, you type it in google and get a link to KnpPaginatorBundle. Start using it and everything goes well, until you hit an error telling you something is wrong. That something is something in the lines of:

  1. SELECT SUM(S.STH) AS something FROM

Which Zend_Paginator does not support! Here is where Pagerfanta comes into the picture.

Download the PagerfantaBundle or get it through git. Also get Pagerfanta. I decided to break PagerfantaBundle into 2 more folders. So the structure of the bundle is now:

  1. vendor\bundles\WhiteOctober\PagerfantaBundle\…

For Pagerfanta, the structure is:

  1. vendor\pagerfanta\src\…

Now, add both to autoload:

  1. // app/autoload.php
  2. $loader->registerNamespaces(array(
  3.     // …
  4.     ‘WhiteOctober’     => __DIR__.‘/../vendor/bundles’,
  5.     ‘Pagerfanta’       => __DIR__.‘/../vendor/pagerfanta/src’,
  6.     // …
  7. ));

Register the bundle with your application kernel:

  1. // app/AppKernel.php
  2. public function registerBundles()
  3. {
  4.     return array(
  5.         // …
  6.         new WhiteOctober\PagerfantaBundle\WhiteOctoberPagerfantaBundle(),
  7.         // …
  8.     );
  9. }

Now what the official documentation does not tell you is what namespaces to include to use it.

For Doctrine2 the example Controller looks like this:

In the view (I assume you are using Twig) you just do:

  1. {{ pagerfanta(examples) }}

And you can be done!

However, there is much more to Pagerfanta. You can pass in many configuration options. Here is where so called Global Variables come in handy. You can define them in app/config/config.yml:

  1. twig:
  2.     globals:
  3.         pagerfanta_opts:
  4.             previous_message: ‘«’
  5.             next_message:     ‘»’
  6.             dots_message:     ‘ … ‘

Now you can access the ‘pagerfanta_opts’ in every template:

  1. {{ pagerfanta(examples, ‘default’, pagerfanta_opts) }}

Where ‘default’ is the name of the Pagerfanta view.

For those who want to learn more about it, read the documentation on GitHub for Pagerfanta.