我正在使用KnpPaginatorBundle,我在Repository中使用QueryBuilder来选择数据。我想知道如何在查询中传递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>
动作控制器:
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();
}
答案 0 :(得分:1)
排序是在数据库层上处理(使用mysql ORDER BY
),因此您无法从getResult()
传递数据数组。您必须将QueryBuilder
实例作为目标传递给paginate()
电话。 KnpPaginator有特殊的Listener和Walker,它可以根据请求使用正确的ORDER BY
修改您的查询,然后为您执行分页。
<强> TravelReopsitory:强>
public function getListTravelsFrontendQueryBuilder()
{
$qb = $this->createQueryBuilder('t')
->leftJoin('t.image', 'i')
->addSelect('i')
->leftJoin('t.agence', 'a')
->addSelect('a')
->Where('t.enabled = 1');
return $qb;
}
动作控制器:
public function listAction($page, Request $request)
{
$em = $this->getDoctrine()->getManager();
$paginator = $this->get('knp_paginator');
$qb = $em->getRepository('ProjectTravelBundle:Travel')->getListTravelsFrontendQueryBuilder();
$pagination = $paginator->paginate(
$qb,
$request->query->get('page', $page)/*page number*/,
10/*limit per page*/
);
return $this->render('ProjectFrontendBundle:Frontend:list.html.twig',array(
'pagination' => $pagination
));
}