简体   繁体   English

使用symfony2使用GET方法从表单中检索数据

[英]Retrieve data from a form with GET method using symfony2

I can't retrieve data from my form, I tried differents ways but no result. 我无法从我的表单中检索数据,我尝试了不同的方法,但没有结果。 My repository : 我的存储库:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('min_price', 'text', array('mapped' => false, 'label' => 'De la :', 'attr'=>
                                       array(
                                            'placeholder'=>'Pretul minim',
                                            'class'=>'form-control')))
            ->add('max_price', 'text', array('mapped' => false, 'label' => 'Pina la :' , 'attr'=>
                                        array(
                                            'placeholder'=>'Pretul maxim',
                                            'class'=>'form-control')))


            )
    ;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    parent::setDefaultOptions($resolver);
    $resolver->setDefaults(array(
        // avoid to pass the csrf token in the url (but it's not protected anymore)
        'csrf_protection' => false,
    ));
}

public function getName()
{
    return '';
}

My controller : 我的控制器:

public function showCategoryAction($id, $page, Request $request){
    $em = $this->getDoctrine()->getManager();
    $repositoryProduct = $em->getRepository('ShopDesktopBundle:Product');

    $category = $em->getRepository('ShopDesktopBundle:Category')->findOneById($id);
    if (!$category) {
        throw $this->createNotFoundException('Category not found.');
    }
    $aFilter = array();

    $entity = new Product();
    $form = $this->createForm(new ProductType(), $entity,array(
        'action' => $this->generateUrl('show_product_category',array("id" => $id, "name" => $category->getCategoryLink(), "page" => $page )), //Your url to generate
        'method' => 'GET'
    ));
    $form->handleRequest($request);
    $aFilter['iMinPrice'] = $form["min_price"]->getData();
    $aFilter['iMaxPrice'] = $form["max_price"]->getData();
    print_r($aFilter);

    //Searchs products
    $aProducts          = $repositoryProduct->getProductsOrderByDateDesc($id,null,$aFilter);
    if (!$aProducts) {
        throw $this->createNotFoundException('Products 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()
    ));
}

My view : 我的观点 :

<form action="{{ path('show_product_category',{ 'id':category.getId(), 'name':category.getCategoryLink() }) }}" method="get" {{ form_enctype(form) }}>
                        <div class="accordion-group">
                            <div class="accordion-heading">
                                <a class="accordion-toggle" data-toggle="collapse" data-parent="" href="#toggleOne">
                                    <em class="icon-minus icon-fixed-width"></em>Pret
                                </a>
                            </div>
                            <div id="toggleOne" class="accordion-body collapse in">
                                <div class="accordion-inner">
                                    {{ form_widget(form) }}
                                </div>
                            </div>
                        </div>
                        <input type="submit" class="btn btn-primary marg-left-20" value="Cautare"/>
                    </form>

The view : 风景 :

show_product_category:
path:     /{id}/{name}/{page}
defaults: { _controller: ShopDesktopBundle:Category:showCategory, page: 1}
requirements:
    id:  \d+
    page: \d+
    _method:  GET|POST

So the problem is that I can't retrieve data from thi form. 所以问题是我无法从该表单中检索数据。 For all situations $aFilter is empty. 对于所有情况,$ aFilter为空。 If for example I put in the view in form POST method the filter is with data from form. 例如,如果我在表单POST方法中放入视图,则过滤器使用表单中的数据。 My url look like this : ?min_price=10&max_price=50. 我的网址看起来像这样:?min_price = 10&max_price = 50。 Help me please. 请帮帮我。 Thx in advance.Exist a solution?? Thx提前。解决方案?

I would not set the form method as GET , just do not specify a method and it will default to POST , which is the usual way to submit a form. 我不会将表单方法设置为GET ,只是不指定方法,它将默认为POST ,这是提交表单的常用方法。

Then handle the form submission in your Controller when the method is POST - like this: 然后在方法POST时在Controller处理表单提交 - 如下所示:

if ($request->isMethod('POST')) {
    $form->handleRequest($request);

    if ($form->isValid() {
        $aFilter['iMinPrice'] = $form->get('min_price')->getData();
        $aFilter['iMaxPrice'] = $form->get('max_price')->getData();
    }
}

More information on how to handle form submissions in Symfony2 here . 有关如何在Symfony2中处理表单提交的更多信息,请参见此处


If you really need the form method to be GET , you should be able to get the query string parameters from the request: 如果你真的需要表单方法是GET ,你应该能够从请求中获取查询字符串参数:

$aFilter['iMinPrice'] = $request->query->get('min_price');
$aFilter['iMaxPrice'] = $request->query->get('max_price');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM