Developed with love by KnpLabs Hire us for your project!
647

KnpPaginatorBundle

by KnpLabs

SEO friendly Symfony2 paginator to sort and paginate

Intro to KnpPaginatorBundle

SEO friendly Symfony2 paginator to paginate everything

Build Status

Generally this bundle is based on Knp Pager component. This
component introduces a different way for pagination handling. You can read more about the
internal logic on the given documentation link.

knpbundles.com

Note: Keep knp-components in sync with this bundle. If you want to use
older version of KnpPaginatorBundle - use v1.0 tag in the repository which is
suitable to paginate ODM mongodb and ORM 2.0 queries

Latest updates

For notes about latest changes please read CHANGELOG,
for required changes in your code please read UPGRADE
chapter of documentation.

Requirements:

  • Knp pager component >=1.1
  • KnpPaginatorBundle's master compatible with symfony (>=2.0 versions).
  • Twig>=1.5 version is required if you use twig templating engine

Features:

  • Does not require initializing specific adapters
  • Can be customized in any way needed, etc.: pagination view, event subscribers.
  • Possibility to add custom filtering, sorting functionality depending on request parameters.
  • Separation of concerns, paginator is responsible for generating the pagination view only, pagination view - for representation purposes.

Note: using multiple paginators requires setting the alias in order to keep non
conflicting parameters. Also it gets quite complicated with a twig template, since hash arrays cannot use
variables as keys.

More detailed documentation:

Installation and configuration:

Pretty simple with Composer, run:

composer require knplabs/knp-paginator-bundle

Configuration example

You can configure default query parameter names and templates

knp_paginator:
    page_range: 5                      # default page range used in pagination control
    default_options:
        page_name: page                # page query parameter name
        sort_field_name: sort          # sort field query parameter name
        sort_direction_name: direction # sort direction query parameter name
        distinct: true                 # ensure distinct results, useful when ORM queries are using GROUP BY statements
    template:
        pagination: KnpPaginatorBundle:Pagination:sliding.html.twig     # sliding pagination controls template
        sortable: KnpPaginatorBundle:Pagination:sortable_link.html.twig # sort link template

Add PaginatorBundle to your application kernel

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

Usage examples:

Controller

Currently paginator can paginate:

  • array
  • Doctrine\ORM\Query
  • Doctrine\ORM\QueryBuilder
  • Doctrine\ODM\MongoDB\Query\Query
  • Doctrine\ODM\MongoDB\Query\Builder
  • Doctrine\Common\Collection\ArrayCollection - any doctrine relation collection including
  • ModelCriteria - Propel ORM query
  • array with Solarium_Client and Solarium_Query_Select as elements
// Acme\MainBundle\Controller\ArticleController.php

public function listAction(Request $request)
{
    $em    = $this->get('doctrine.orm.entity_manager');
    $dql   = "SELECT a FROM AcmeMainBundle:Article a";
    $query = $em->createQuery($dql);

    $paginator  = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $query,
        $request->query->get('page', 1)/*page number*/,
        10/*limit per page*/
    );

    // parameters to template
    return $this->render('AcmeMainBundle:Article:list.html.twig', array('pagination' => $pagination));
}

View

{# total items count #}
<div class="count">
    {{ pagination.getTotalItemCount }}
</div>
<table>
<tr>
{# sorting of properties based on query components #}
    <th>{{ knp_pagination_sortable(pagination, 'Id', 'a.id') }}</th>
    <th{% if pagination.isSorted('a.Title') %} class="sorted"{% endif %}>{{ knp_pagination_sortable(pagination, 'Title', 'a.title') }}</th>
</tr>

{# table body #}
{% for article in pagination %}
<tr {% if loop.index is odd %}class="color"{% endif %}>
    <td>{{ article.id }}</td>
    <td>{{ article.title }}</td>
</tr>
{% endfor %}
</table>
{# display navigation #}
<div class="navigation">
    {{ knp_pagination_render(pagination) }}
</div>

Translation in view

For translating the following text:
* %foo% name with translation key table_header_name. The translation is in the domain messages.
* {0} No author|{1} Author|[2,Inf] Authors with translation key table_header_author. The translation is in the domain messages.

translationCount and translationParameters can be combined.

<table>
    <tr>
{# sorting of properties based on query components #}
       <th>{{ knp_pagination_sortable(pagination, 'Id'|trans({foo:'bar'},'messages'), 'a.id' )|raw }}</th>
       <th{% if pagination.isSorted('a.Title') %} class="sorted"{% endif %}>{{ knp_pagination_sortable(pagination, 'Title', 'a.title')|raw }}</th>
       <th>{{ knp_pagination_sortable(pagination, 'Author'|trans({}, 'messages'), 'a.author' )|raw }}</th>
    </tr>

<!-- Content of the table -->

</table>

Dependency Injection

You can automatically inject a paginator service into another service by using the knp_paginator.injectable DIC tag.
The tag takes one optional argument paginator, which is the ID of the paginator service that should be injected.
It defaults to knp_paginator.

The class that receives the KnpPaginator service must implement Knp\Bundle\PaginatorBundle\Definition\PaginatorAwareInterface.
If you're too lazy you can also just extend the Knp\Bundle\PaginatorBundle\Definition\PaginatorAware base class.

XML configuration example
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="my_bundle.paginator_aware.class">MyBundle\Repository\PaginatorAwareRepository</parameter>
    </parameters>

    <services>
        <service id="my_bundle.paginator_aware" class="my_bundle.paginator_aware.class">
            <tag name="knp_paginator.injectable" paginator="knp_paginator" />
        </service>
    </services>
</container>
Copyright (c) 2011 Knplabs

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
knp_paginator:
default_options:
sort_field_name: sort
sort_direction_name: direction
filter_field_name: filterField
filter_value_name: filterValue
page_name: page
distinct: true
template:
pagination: KnpPaginatorBundle:Pagination:sliding.html.twig
filtration: KnpPaginatorBundle:Pagination:filtration.html.twig
sortable: KnpPaginatorBundle:Pagination:sortable_link.html.twig
page_range: 5
  • Merge pull request #291 from disquedur/master
    By pilot, 5 months ago
  • Merge pull request #292 from oohnoitz/tests
    By pilot, 5 months ago
  • switched to PSR-4 autoloading and fixed tests
    By oohnoitz, 5 months ago
  • Fixed loading of php templating helper when php engine isn't enabled
    By , 5 months ago
  • Merge pull request #241 from gnat42/patch-1
    By pilot, 7 months ago
  • Merge pull request #211 from alvaro-rm/master
    By pilot, 7 months ago
  • Merge pull request #265 from vierbergenlars/patch-1
    By pilot, 7 months ago
  • Merge pull request #281 from lucasaba/documentation-typos
    By pilot, 7 months ago
  • Merge pull request #280 from taavit/patch-1
    By pilot, 7 months ago
  • Merge pull request #279 from rdohms/patch-1
    By pilot, 7 months ago
  • Merge pull request #269 from Nek-/master
    By pilot, 7 months ago
  • Correct some small typos in documentation
    By Luca Saba, 7 months ago
  • Update README.md
    By taavit, 7 months ago
  • Update README.md
    By rdohms, 8 months ago
  • Update README.md
    By Nek-, 9 months ago
  • Merge pull request #264 from tavish/patch-1
    By Shivoham, 9 months ago
  • Merge pull request #266 from KnpLabs/fix/tests
    By pilot, 10 months ago
  • Make it green
    By akovalyov, 10 months ago
  • [docs] Update templates.md twig syntax
    By vierbergenlars, 10 months ago
  • Update KnpPaginatorBundle.php
    By tavish, 10 months ago
  • Merge pull request #226 from Astrac/master
    By docteurklein, 10 months ago
  • Merge pull request #248 from methylbro/master
    By wysow, 11 months ago
  • Merge pull request #259 from Nyholm/master
    By pilot, 11 months ago
  • Added travis
    By Nyholm, 11 months ago
  • Merge pull request #229 from sroze/patch-1
    By docteurklein, 1 year ago
  • Merge pull request #253 from cloudson/patch-1
    By Inoryy, 1 year ago
  • Fix typo
    By cloudson, 1 year ago
  • fix #224 Allow class name passthrough not only when sorted
    By methylbro, 1 year ago
  • recovery of maintenance of the project
    By wysow, 1 year ago
  • add a note about maintenance of the project
    By Inoryy, 1 year ago