如何从symfony2中的表单中获取数据 [英] How to get data from a form in symfony2
本文介绍了如何从symfony2中的表单中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法:
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 变量为空.我不明白我的问题在哪里,可能我错过了一些东西.创建未在控制器中映射的表单是个好主意?请帮我.提前谢谢
I search and normally everything is ok but my $var variable is null. I don't understand where is my problem, probably I missing something. It's a good idea to create forms who is not mapped in controller?. Please help me. Thx in advance
推荐答案
如果你使用的是 Symfony 2.3 你可以这样做:
If you are using Symfony 2.3 you can do it this way:
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
:
Also, in case I doesn't work or the $request
is empty, you can also get the $request
in another way:
public function showCategoryAction($id, $page) {
$request = $this->get('request');
//...
}
这篇关于如何从symfony2中的表单中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文