[英]How to get data from a form in 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变量为null。 我不明白我的问题出在哪里,可能我错过了一些东西。 创建不在控制器中映射的表单是一个好主意。 请帮我。 提前Thx
if ('POST' === $request->getMethod())
{
$form->bindRequest($request); //Symfony 2.0.x
//$form->bind($request); //Symfony 2.1.x
$name = $form->get('name')->getData();
}
我不在岸上,但这应该对你有用
如果您使用的是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');
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.