I'm using KnpPaginatorBundle and I'm using QueryBuilder in Repository to select data. I was obliged to put parameters sort and direction in variables $sort and $direction and pass them to the Query to be able to do and orderBy.
This code works but I'd like to show it to you and and have your opinions if it's a good way to do this with KnpPaginatorBundle or there is another better way provided by knpPaginatorBundle.
Can I pass those parameters directly to knp_paginator not in the queryBuilder ?
Action
public function listAction($page, Request $request)
{
$em = $this->getDoctrine()->getManager();
$paginator = $this->get('knp_paginator');
if($request->query->get('sort') and $request->query->get('direction')) {
$sort = $request->query->get('sort') ;
$direction = $request->query->get('direction');
}
else{
$sort = 'id'; // set default sort
$direction = 'asc'; // set default direction
}
// pass those two variables to query
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->getListTravelsFrontend($sort, $direction);
$pagination = $paginator->paginate(
$listTravels,
$this->get('request')->query->get('page', $page)/*page number*/,
10/*limit per page*/
);
return $this->render('ProjectFrontendBundle:Frontend:list.html.twig',array(
'pagination' => $pagination
));
}
TravelRepository:
public function getListTravelsFrontend($sort, $direction) // parameters $sort, $direction
{
$qb = $this->createQueryBuilder('t')
->leftJoin('t.image', 'i')
->addSelect('i')
->leftJoin('t.agence', 'a')
->addSelect('a')
->Where('t.enabled = 1')
->orderBy('t.'.$sort, $direction); // orderBy with those parameters
return $qb->getQuery()->getResult();
}
@phpisuber01 is right, his answer helps me understand. Unfortunately, official KnpPaginator site does not give example for QueryBuilder but does mention /* query NOT result */ in https://github.com/KnpLabs/KnpPaginatorBundle.
Here is the example code for QueryBuilder:
First in Repository:
Second in Controller:
Third in View:
That is it.