I'm using KnpPaginatorBundle and I'm using QueryBuilder in Repository to select data. I'd like to know how can I pass parameters sort and direction sent by Form in the query.
This is th form:
<form action="" method="get" class="form_sort" id="myForm">
<span class="manage_title">Sort by:</span>
<select class="select_styled white_select" id="sort_list" name="option">
<option value="">-------</option>
{{ knp_pagination_sortable(pagination, 'Country A-Z', 'country', {'sort': 'country', 'direction': 'asc'}) }}
{{ knp_pagination_sortable(pagination, 'Country Z-A', 'country', {'sort': 'country', 'direction': 'desc'}) }}
{{ knp_pagination_sortable(pagination, 'City A-Z', 'destination', {'sort': 'destination', 'direction': 'asc'}) }}
{{ knp_pagination_sortable(pagination, 'City Z-A', 'destination', {'sort': 'destination', 'direction': 'desc'}) }}
</select>
</form>
Action Controller:
public function listAction($page, Request $request)
{
$em = $this->getDoctrine()->getManager();
$paginator = $this->get('knp_paginator');
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->getListTravelsFrontend();
$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
));
}
TravelReopsitory:
public function getListTravelsFrontend()
{
$qb = $this->createQueryBuilder('t')
->leftJoin('t.image', 'i')
->addSelect('i')
->leftJoin('t.agence', 'a')
->addSelect('a')
->Where('t.enabled = 1');
return $qb->getQuery()->getResult();
}
Sorting is handle on database layery (using mysql
ORDER BY
) so you can't pass array of data fromgetResult()
. You would have to passQueryBuilder
instance as a target to youpaginate()
call. KnpPaginator have special Listener and Walker that can modify your query with correctORDER BY
based on request and then eqecute an paginate it for you.TravelReopsitory:
Action Controller: