我有一个方法:
public function showCategoryAction($id, $page, Request $request){
$em = $this->getDoctrine()->getManager();
$repositoryProduct = $em->getRepository('ShopDesktopBundle:Product');
$aFilter = array();
$form = $this->get('form.factory')->createNamedBuilder('', 'form', null, array(
'csrf_protection' => false,
))
->setMethod('GET')
->add('minimPrice', 'text', array('mapped' => false, 'label' => 'De la :' , 'attr'=>
array(
'placeholder'=>'Minim price',
'class'=>'form-control')))
->add('maxPrice', 'text',array('mapped' => false, 'label' => 'Pina la :' , 'attr'=>
array(
'placeholder'=>'Max price',
'class'=>'form-control')))
->getForm();
$form->handleRequest($request);
$var = $form->get('minimPrice')->getData();
print_r($var);
//Search products
$aProducts = $repositoryProduct->getProductsOrderByDateDesc($id,null,$aFilter);
if (!$aProducts) {
throw $this->createNotFoundException('Products not found.');
}
$category = $em->getRepository('ShopDesktopBundle:Category')->findOneById($id);
if (!$category) {
throw $this->createNotFoundException('Category not found.');
}
//Create pagination
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$aProducts,
$page,
3
);
//Send data to view
return $this->render('ShopDesktopBundle:Category:category.html.twig',array(
'category' => $category,
'pagination' => $pagination,
'form' => $form->createView()
));
}
我的观点:
<form action="{{ path('show_product_category',{ 'id':category.getId(), 'name':category.getCategoryLink() }) }}" method="get" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<input type="submit" class="btn btn-primary marg-left-20" value="Search"/>
</form>
我搜索并且通常一切正常,但我的$ var变量为null。我不明白我的问题在哪里,可能是我遗漏了什么。创建未映射到控制器中的表单是个好主意?请帮我。 Thx提前
答案 0 :(得分:0)
if ('POST' === $request->getMethod())
{
$form->bindRequest($request); //Symfony 2.0.x
//$form->bind($request); //Symfony 2.1.x
$name = $form->get('name')->getData();
}
我不确定,但这应该对你有用
答案 1 :(得分:0)
如果您使用的是Symfony 2.3,可以这样做:
public function showCategoryAction($id, $page, Request $request) {
//...
$form = // whatever...
if ($request->isMethod('POST'))
{
$form->submit($request);
if ($form->isValid())
{
// Do your magic!
// Persist your form, send email, blablabla...
return $this->redirect($this->generateUrl('your_url_to_show'));
}
}
return $this->render(/*same code you have...*/);
}
此外,如果我无法工作或$request
为空,您还可以通过其他方式获取$request
:
public function showCategoryAction($id, $page) {
$request = $this->get('request');
//...
}