Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use KNPPaginatorBundle to paginate results using Doctrine Repository?

I'm working on a Symfony2 project and I decided to use KNPPaginatorBundle to build an easy pagination system. So I created a Product entity and I want to add the paginator to indexAction action (generated by CRUD command).

// Retrieving products.
$em = $this->getDoctrine()->getManager();

//$entities = $em->getRepository('LiveDataShopBundle:Product')->findAll();

$dql   = "SELECT a FROM LiveDataShopBundle:Product a";
$entities = $em->createQuery($dql);

// Creating pagnination
$paginator  = $this->get('knp_paginator');
$pagination = $paginator->paginate(
    $entities,
    $this->get('request')->query->get('page', 1),
    20
);

It works fine but I want to use the Product's repository instead of creating the query directly in the controller. How can I do that ? In fact, directly add the collection of results to the paginate object is just too slow because its load all products then paginate the ArrayCollection.

Thanks in advance.

K4

like image 813
K4timini Avatar asked Apr 02 '14 07:04

K4timini


1 Answers

I suggest using QueryBuilder in your ProductRepository and then passing that to the paginator:

ProductRepository extends EntityRepository
{
    // This will return a QueryBuilder instance
    public function findAll()
    {
        return $this->createQueryBuilder("p");
    }
}

In the controller:

$products = $productRepository->findAll();

// Creating pagnination
$paginator  = $this->get('knp_paginator');
$pagination = $paginator->paginate(
    $products,
    $this->get('request')->query->get('page', 1),
    20
);
like image 58
Alberto Fernández Avatar answered Sep 23 '22 21:09

Alberto Fernández