访问 Symfony2 请求对象中的 POST 值 [英] Access POST values in Symfony2 request object
问题描述
好的,这是一个新手问题,但我在任何地方都找不到答案.在 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();
给你一个表单参数数组
来自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 值(在本例中为名称"),如下所示:
You can also access POST values (in this case "name") directly through the request object, like so:
$this->get('request')->request->get('name');
但是请注意,在大多数情况下,使用 getData() 方法是更好的选择,因为它返回表单框架转换后的数据(通常是对象).
当你想访问表单令牌时,你必须使用Problematica的答案$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屋!