Pagination in Symfony2 with KnpPaginatorBundle

Pagination is always nice in an application. I found a great bundle called KnpPaginatorBundle that helps you with pagination and as an bonus we also get sorting.

So as usual we need to add some bundles to our deps file:

[Zend]
    git=git://github.com/zendframework/zf2.git
    target=/Zend 

[knp-components]
    git=http://github.com/knplabs/knp-components.git

[KnpPaginatorBundle]
    git=https://github.com/knplabs/KnpPaginatorBundle.git
    target=/bundles/Knp/Bundle/PaginatorBundle

As you can see the KnpPaginatorBundle uses Zend for the pagination.

Add the following to your app/autoload.php

$loader->registerNamespaces(array(
    'Knp\\Component'      => __DIR__.'/../vendor/knp-components/src',
    'Knp'                 => __DIR__.'/../vendor/bundles',
    'Zend'                => __DIR__.'/../vendor/Zend/library',
    // ...
));

And to the app/AppKernel.php we need to add this:

public function registerBundles()
{
    return array(
        // ...
        new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(),
        // ...
    );
}

Almost done.. we just need to enable it in the app/config/config.yml file:

knp_paginator:
    templating: ~ # enables view helper and twig

That is all we need to do to be able to use pagination and sorting 🙂 Below follows an example on a Person Entity

//src/MLK/BackEndBundle/Controller/PersonController.php
...
    /**
     * Lists all Person entities.
     *
     * @Route("/", name="person")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $dql = "Select a from MLKBackEndBundle:Person a";
        $query = $em->createQuery($dql);

        $adapter = $this->get('knp_paginator.adapter');
        $adapter->setQuery($query);
        $adapter->setDistinct(true);

        $paginator = new \Zend\Paginator\Paginator($adapter);
        $paginator->setCurrentPageNumber($this->get('request')->query->get('page', 1));
        $paginator->setItemCountPerPage(5);
        $paginator->setPageRange(5);

        return array('paginator' => $paginator);
    }
...
//src/MLK/BackEndBundle/Resources/views/Person/index.html.twig
{% extends '::base.html.twig' %}
{% block body %}

Person list

{# table body #} {% for entity in paginator %}{% endfor %}
{{ paginator|sortable('Id', 'a.id') }} {{ paginator|sortable('Firstname', 'a.firstName') }} {{ paginator|sortable('Lastname', 'a.lastName') }} {{ paginator|sortable('Birthday', 'a.birthday') }} Actions
{{ entity.id }} {{ entity.firstName }} {{ entity.lastName }} {% if entity.birthday %}{{ entity.birthday|date('Y-m-d') }}{% else %}No Value{% endif %}
{# display navigation #} {% endblock %}

For more information see https://github.com/knplabs/KnpPaginatorBundle.

Keep it real!

13 Responses to “Pagination in Symfony2 with KnpPaginatorBundle”

  1. retropixel

    Thanks Mikael!

    Excellent tutorial, i’ve been struggling with the KnpPaginatorBundle setup until I found your blog 🙂

  2. tensai

    you forgot

    in deps:
    [knp-components]
    git=http://github.com/knplabs/knp-components.git

    in autoload.php
    ‘Knp\\Component’ => __DIR__.’/../vendor/knp-components/src’,

  3. Mikael Ohlsson

    Thanks for your comment tensai. When I wrote this post there where no dependency on knp-components, that is a new requirement. I have now updated the info.

  4. tensai

    Hi Michael. I don’t know if more change have been made but I am running into the following error.

    You have requested a non-existent service “knp_paginator.adapter”.

    I have the following in config.yml:

    knp_paginator:
    templating: ~ # enables view helper and twig

    Am I missing something?

  5. Simon

    Is there a way to influence the generated URLs?
    I don’t want to have those query strings in my URLs (e.g. ?page=3&sort=something)… So it’d be great if there is a possibility to modify the generated URL.

    And how can I disable prefixing the entitiys name? e.g. a.property. I want the bundle to only use “property” insteaf of “a.property” if it’s possible.

    Looking forward to your tips 🙂

    Simon

  6. Simon

    Is there a way to influence the generated URLs?
    I don’t want to have those query strings in my URLs (e.g. ?page=3&sort=something)… So it’d be great if there is a possibility to modify the generated URL.

    And how can I disable prefixing the entitiys name? e.g. a.property. I want the bundle to only use “property” insteaf of “a.property” if it’s possible.

    Looking forward to your tips 🙂

    Kind regards
    Simon

  7. Saravanan

    I am using a PHP template engine .The Code here is for twig template engine.i need sample code for using this in php template engine

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>