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');
Unfortunately $name_value
isn't returning anything. What am I doing wrong? Thanks!
The form post values are stored under the name of the form in the request. For example, if you've overridden the getName()
method of ContactType() to return "contact", you would do this:
$postData = $request->request->get('contact'); $name_value = $postData['name'];
If you're still having trouble, try doing a var_dump()
on $request->request->all()
to see all the post values.
this solution is deprecated since 2.3 and will be removed in 3.0, see documentation
$form->getData();
gives you an array for the form parameters
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 }
You can also access POST values (in this case "name") directly through the request object, like so:
$this->get('request')->request->get('name');
Be advised, however, that in most cases using the getData() method is a better choice, since it returns the data (usually an object) after it's been transformed by the form framework.
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
since 2.3 you should use handleRequest
instead of bindRequest
:
$form->handleRequest($request);
see documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With