我正在创建一个修改 KnpPaginatorBundle 查询的表单,以显示过滤后的分页结果。
要做到这一点。当表单有效时,我使用所需字段构建查询字符串(连接)以进行过滤。我使用自定义查询设置了 $filteredDql 变量。问题是它的价值只保留在第一页。当我更改页面时,它变为 NULL。并且分页重置...
我认为,问题可能是我在块上下文中设置了 $filteredDql 变量(仅当表单有效时)。
如何为整个操作或应用程序范围设置 $filteredDql 变量?也许使用参数?我尝试使用控制器中的容器但未成功使用:
$this->container->setParameter('key', value);
$this->container->getParameter('key');
$this->container->HasParameter('key');
但这样我得到500 Internal Server Error
这是代码:
public function indexAction(Request $request, $page)
{
$filters = new Filters();
$form = $this->createForm(new FiltersType(), $filters);
$dql = "SELECT a FROM ViciousAmateurBundle:Post a WHERE a.is_active = true";
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
$country = $filters->getCountry();
$city = $filters->getCity();
$gender = $filters->getGender();
$sexualOrientation = $filters->getSexualOrientation();
if (isset($country)) {
$dql .= " AND a.country = '" . $filters->getCountry() . "'";
}
if (isset($city)) {
$dql .= " AND a.city = '" . $filters->getCity() . "'";
}
if (isset($gender)) {
$dql .= " AND a.gender = '" . $filters->getGender() . "'";
}
if (isset($sexualOrientation)) {
$dql .= " AND a.sexual_orientation = '" . $filters->getSexualOrientation() . "'";
}
$filteredDql = $dql;
}
}
$em = $this->get('doctrine.orm.entity_manager');
if (isset($filteredDql)) {
$query = $em->createQuery($filteredDql);
} else {
$query = $em->createQuery($dql);
}
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$this->get('request')->query->get('page', $page),
5
);
return $this->render('ViciousAmateurBundle:Default:index.html.twig', array(
'form' => $form->createView(),
'pagination' => $pagination
)
);
}