Video tutorial for KnpPaginatorBundle – pagination in Symfony2

Hi guys! Today I'm going to create a new tutorial for Symfony2. In this tutorial I will explain to you how you can use pagination in Symfony2.

I found a cool plugin for Symfony2, called KnpPaginatorBundle. With KnpPaginatorBundle you can easily add pagination in your Symfony2 project.

To create this tutorial, I will follow the KnpPaginatorBundle'documentation:

  • Open your command line in your Symfony project and enter: php composer.phar require knplabs/knp-paginator-bundle
  • Next, open app/AppKernel.php file and add new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(),
  • Crea a new action in your controller:

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));
}

  • And add in your view file this code:

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

Video tutorial:









Leave a Comment