2

I've the basic form, template and controller action of Symfony2 documentation for this example.

Whenever I try to get a parameter of the form in controller action I have to use this:

$parameters = $request->request->all();
$name = $parameters["form"]["name"];

However, in documentation use this:

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

But this is wrong for me, in this case $name is null and the Object request(ParameterBag) contain this:

object(Symfony\Component\HttpFoundation\ParameterBag)#8 (1) {
  ["parameters":protected]=>
  array(1) {
    ["form"]=>
    array(1) {
      ["name"]=>
      string(4) "test"
    }
  }
}
2
  • Did you use a formType to generate the form? If so what does the getName() function return. Commented Nov 14, 2012 at 12:59
  • I agree @Biruton. Documentation is misleading. Commented May 3, 2014 at 14:14

1 Answer 1

11
$formPost = $request->request->get('form');
$name = $formPost['name'];

Or since PHP 5.4

$name = $request->request->get('form')['name'];

On my opinion, the best way to access submitted data is firstly to bind the request to the form, and then to access values from the Form object :

if ('POST' === $request->getMethod())
{
    $form->bindRequest($request); //Symfony 2.0.x
    //$form->bind($request); //Symfony 2.1.x

    $name = $form->get('name')->getData();
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for binding (in that way you can accomplish validation also)
Your first example $name = $request->request->get('form')['name']; will only work in PHP 5.4. FWIW.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.