【问题标题】:Retrieve data from a form with GET method using symfony2使用 symfony2 使用 GET 方法从表单中检索数据
【发布时间】:2015-06-13 20:36:51
【问题描述】:

我无法从表单中检索数据,我尝试了不同的方法但没有结果。我的仓库:

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 '';
}

我的控制器:

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()
    ));
}

我的看法:

<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>

观点:

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

所以问题是我无法从这个表单中检索数据。对于所有情况,$aFilter 都是空的。例如,如果我在表单 POST 方法中放入视图,则过滤器包含表单中的数据。我的网址如下所示: ?min_price=10&max_price=50。 请帮帮我。提前谢谢。有解决方案吗??

【问题讨论】:

  • 你能试试$form-&gt;get("min_price")-&gt;getData();吗?
  • 不行,数组为空

标签: php symfony symfony-forms php-5.3 symfony-2.3


【解决方案1】:

我不会将表单方法设置为GET,只是不指定方法,它将默认为POST,这是提交表单的常用方式。

然后在方法为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();
    }
}

更多关于如何在 Symfony2 here 中处理表单提交的信息。


如果确实需要form方法为GET,应该可以从请求中获取查询字符串参数:

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

【讨论】:

  • 我需要将方法设置为“GET”而不是“POST”
  • 我也尝试了 $_GET 但没有结果: if (isset($_GET['min_price'])){ $test = $_GET['min_price']; print_r($test); }
  • 我试过了,但没用:网址是:?min_price=1&max_price=111111 但aFilter 为空
猜你喜欢
  • 2016-03-24
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多