访问Symfony2请求对象中的POST值 [英] Access POST values in Symfony2 request object

查看:191
本文介绍了访问Symfony2请求对象中的POST值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这是一个新手问题,但我无法在任何地方找到答案。在Symfony2的控制器中,我想从我的一个表单中访问POST值。在控制器中我有:

OK, this is a newbie question, but I can't find the answer anywhere. In a controller in Symfony2, I want to access the POST value from one of my forms. In the controller I have:

public function indexAction()
{ 
    $request = $this->get('request');
    if ($request->getMethod() == 'POST') {
        $form = $this->get('form.factory')->create(new ContactType());
        $form->bindRequest($request);
        if ($form->isValid()) {
            $name_value = $request->request->get('name');

不幸的是 $ name_value 没有返回任何东西。我究竟做错了什么?谢谢!

Unfortunately $name_value isn't returning anything. What am I doing wrong? Thanks!

推荐答案

Symfony 2.2



此解决方案自2.3以来已弃用删除3.0,请参阅文档

$form->getData();

为您提供表格参数的数组

gives you an array for the form parameters

来自 symfony2 book 第162页(第12章:表格)

from symfony2 book page 162 (Chapter 12: Forms)

[...]有时,您可能只想使用没有类的表单,并获取提交的
数据的数组。这实际上非常简单:

[...] sometimes, you may just want to use a form without a class, and get back an array of the submitted data. This is actually really easy:

public function contactAction(Request $request) {
  $defaultData = array('message' => 'Type your message here');
  $form = $this->createFormBuilder($defaultData)
  ->add('name', 'text')
  ->add('email', 'email')
  ->add('message', 'textarea')
  ->getForm();
  if ($request->getMethod() == 'POST') {
    $form->bindRequest($request);
    // data is an array with "name", "email", and "message" keys
    $data = $form->getData();
  }
  // ... render the form
}

您也可以直接通过请求对象访问POST值(在本例中为name),如下所示:

You can also access POST values (in this case "name") directly through the request object, like so:

$this->get('request')->request->get('name');

但请注意,在大多数情况下使用getData()方法更好选择,因为
在表单框架转换后返回数据(通常是对象)。

当你想访问时表格令牌,你必须使用有问题的答案
$ postData = $ request-> request-> get('contact'); 因为 getData()从数组中删除元素

When you want to access the form token, you have to use the answer of Problematic $postData = $request->request->get('contact'); because the getData() removes the element from the array

自2.3以来你应该使用 handleRequest 而不是 bindRequest

since 2.3 you should use handleRequest instead of bindRequest:

 $form->handleRequest($request);

参见文档

这篇关于访问Symfony2请求对象中的POST值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆