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:

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:


For Pagerfanta, the structure is:


Now, add both to autoload:

// app/autoload.php
    // ...
    'WhiteOctober'     => __DIR__.'/../vendor/bundles',
    'Pagerfanta'       => __DIR__.'/../vendor/pagerfanta/src',
    // ...

Register the bundle with your application kernel:

// app/AppKernel.php
public function registerBundles()
    return array(
        // ...
        new WhiteOctober\PagerfantaBundle\WhiteOctoberPagerfantaBundle(),
        // ...

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:

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

            prev_message: '«'
            next_message: '»'
            dots_message: ' ... '

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

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