所以我有这个ChoiceType Form
将对项目进行排序:
$sort = $this->createForm(ChoiceType::class, NULL, array(
'choices' => array(
'...' => 'default',
'A-Z' => 'title_up',
'Z-A' => 'title_down',
'Price low to high' => 'price_up',
'Price high to low' => 'price_down',
),
));
我想使用Choices
,以便从下拉菜单中选择其中一个时执行此操作:$products = "SELECT a FROM AppBundle:Product a ORDER BY a.title ASC"
。
我试过了:
$sort->handleRequest($request);
if($sort->isSubmitted() && $sort->isValid()) {
if (isset($default)) {
$products = "SELECT a FROM AppBundle:Product a ORDER BY a.title ASC";
return $this->render('AppBundle:main:index.html.twig', array('products' => $products, ));
}
}
但$default
无效,因为未定义。我不知道如何访问choices
,因此我可以将它们传递给if
语句。
答案 0 :(得分:0)
我认为你需要写下这样的东西:
$sort = $this->createFormBuilder()
->setAction($this->generateUrl('your_process_route_here'))
->setMethod('POST')
->add('select', ChoiceType::class, [
'placeholder' => 'Please select',
'choices' => [
'...' => 'default',
'A-Z' => 'title_up',
'Z-A' => 'title_down',
'Price low to high' => 'price_up',
'Price high to low' => 'price_down',
]
])
要获取<select>
元素中的值:
$select = $request->request->get('select'); // this will contain whatever value you've selected from the dropdown
检查值是否符合预期,然后创建查询:
if ('default' == $select){ // or you can use a switch
// create a custom method inside your Repository class containing the SELECT, and call it here
}
来自select
的{{1}}将是您的->add('select', ...)
html元素的名称属性。