Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parameter of form on Symfony2 controller

Tags:

symfony

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"
    }
  }
}
like image 866
Biruwon Avatar asked Dec 10 '25 13:12

Biruwon


1 Answers

$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();
}
like image 135
AlterPHP Avatar answered Dec 12 '25 12:12

AlterPHP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!