Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the request parameters in Symfony 2?

Tags:

php

symfony

The naming is not all that intuitive:

use Symfony\Component\HttpFoundation\Request;

public function updateAction(Request $request)
{
    // $_GET parameters
    $request->query->get('name');

    // $_POST parameters
    $request->request->get('name');

Update Nov 2021: $request->get('name') has been deprecated in 5.4 and will be private as of 6.0. It's usage has been discouraged for quite some time.


I do it even simpler:

use Symfony\Component\HttpFoundation\Request;

public function updateAction(Request $request)
{
    $foo = $request->get('foo');
    $bar = $request->get('bar');
}

Another option is to introduce your parameters into your action function definition:

use Symfony\Component\HttpFoundation\Request;

public function updateAction(Request $request, $foo, $bar)
{
    echo $foo;
    echo $bar;
}

which, then assumes that you defined {foo} and {bar} as part of your URL pattern in your routing.yml file:

acme_myurl:
    pattern:  /acme/news/{foo}/{bar}
    defaults: { _controller: AcmeBundle:Default:getnews }

You can Use The following code to get your form field values

use Symfony\Component\HttpFoundation\Request;

public function updateAction(Request $request)
{
    // retrieve GET and POST variables respectively
    $request->query->get('foo');
    $request->request->get('bar', 'default value if bar does not exist');
}

Or You can also get all the form values as array by using

$request->request->all()

try

$request->request->get('acme_demobundle_usertype')['username']

inspect attribute name of your formular field


Inside a controller:

$request = $this->getRequest();
$username = $request->get('username');