How to use KNPPaginatorBundle to paginate results using Doctrine Repository?

后端 未结 3 1417
梦如初夏
梦如初夏 2021-02-05 23:46

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 i

3条回答
  •  失恋的感觉
    2021-02-06 00:08

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

提交回复
热议问题