218

I am very new to symfony. In other languages like java and others I can use request.getParameter('parmeter name') to get the value.

Is there anything similar that we can do with symfony2.
I have seen some examples but none is working for me. Suppose I have a form field with the name username. In the form action I tried to use something like this:

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

I have also tried

$username = $request->getParameter('username');

and

$username=$request->request->getParameter('username');

But none of the options is working.However following worked fine:

foreach($request->request->all() as $req){
    print_r($req['username']);
}

Where am I doing wrong in using getParameter() method. Any help will be appreciated.

simhumileco
  • 31,877
  • 16
  • 137
  • 115
Abdul Hamid
  • 3,222
  • 3
  • 24
  • 31
  • You have a typo in line two: `$request->request-get()` should be `$request->request->get()`. Could that be it? – halfer Mar 20 '12 at 11:01
  • have written same in the code.missed out here.sorry for the typo here .still this is not working. – Abdul Hamid Mar 20 '12 at 12:08
  • Have you (a) checked the manual to ensure that `get()` is the correct method and (b) turned on PHP notices so you can see if there are any problems? (c) Does Symfony 2 have a debug toolbar like symfony 1, so you can see if you've made any errors? – halfer Mar 20 '12 at 12:31
  • Are you confusing firstname and username? – greg0ire Mar 20 '12 at 13:09
  • There is more information here : https://roadtodev.com/recuperer-objet-request-de-symfony – Thomas Bredillet Oct 06 '17 at 20:16

16 Answers16

452

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');

    // As of 6.3 Posted or json content
    $request->getPayload()->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.

Update May 2023: As of 6.3, a getPayload method has been added for post/json data.

Cerad
  • 48,157
  • 8
  • 90
  • 92
  • 46
    It is different from what PHP uses, but it actually makes more sense. `$_GET` data is data from the query string (no `GET` request needed at all) and `$_POST` data is data from the request body (does not have to be a `POST` request either, could be `PUT`). – igorw Mar 20 '12 at 15:43
  • 5
    tried $request->query->get('name'); but it is also not working. – Abdul Hamid Mar 21 '12 at 11:55
  • 7
    How do I get the parameters from a PUT request? – Tjorriemorrie Sep 09 '13 at 14:17
  • 10
    Very strange naming here, surely `$request->get` and `$request->post` would be simpler. – crmpicco Jan 07 '16 at 14:02
  • 3
    comment from igorw brings clarity to this freaky naming convention – some_groceries Mar 01 '16 at 06:53
  • But how to get the parameters of PUT request? No docs found for it – S Vinesh May 19 '16 at 09:45
  • If the URL in this format `http://localhost/c2Education/web/dailydata/payment?amount=1000` how can i access. is it right Way.? or any other alternate method to define url. – Snopzer Aug 07 '16 at 22:16
  • Mohammad - if you have the Request object as `$request` then do `$request->query->get('amount')`. See http://symfony.com/doc/current/controller.html#the-request-object-as-a-controller-argument – caponica Aug 24 '16 at 11:28
  • @Tjorriemorrie currently, you can't, unless you do various workarounds, since neither PHP nor Symfony provides proper parsing for those requests (https://stackoverflow.com/questions/9464935/php-multipart-form-data-put-request etc) –  Nov 11 '17 at 21:37
34

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 }
pkout
  • 6,430
  • 2
  • 45
  • 55
  • and in the first example, if I have `foo` parameter both in query string and in POST body, which one will be returned by `$request->get('foo')`? – Dimitry K Aug 27 '14 at 11:52
  • 2
    Looks like precedence is GET, PATH, POST http://api.symfony.com/master/Symfony/Component/HttpFoundation/Request.html#method_get – Dimitry K Aug 27 '14 at 11:55
  • This is the best answer – steampowered Feb 18 '15 at 23:55
  • 7
    No it's not. The documentation of the method itself says it is discouraged to use it because it's heavier than accessing the GET/POST parameters through their specific collections. – jurchiks Jan 31 '16 at 15:42
  • **This answer is actually wrong!** `$request->get('foo');` will work for POST, but not for GET variables in Symfony2. – Sliq Feb 17 '17 at 08:54
  • 2
    **Answer is correct** `$request->get('foo');` works for ALL bags (order is : PATH, GET, POST). Nevertheless, `$request->request->get('foo');` works only for POST bag. Finally, the first one (`$request->get()`) is not recommended if we know where the data is (GET/POST). – F2000 Oct 30 '17 at 09:08
21

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()
ScoRpion
  • 11,364
  • 24
  • 66
  • 89
13

try

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

inspect attribute name of your formular field

MartinW.
  • 131
  • 1
  • 4
  • 1
    +1, since I think that of all the responses, only this one actually states the non-obvious thing - in cases you have created your forms automatically with help of symfony's form builder, symfony renames the form field to something more than you'd expect. Like name="acme_demobundle_userform[field_name]" – userfuser Apr 23 '14 at 12:27
  • Syntax you mentioned here is not working with php 5.3.10. What is minimum version to support that? – Justinas Lelys Jul 29 '14 at 10:14
  • 2
    @justinasLelys try $userType = $request->request->get('acme_demobundle_usertype'); $username = $userType['username']; – sleep-er Aug 08 '14 at 15:33
  • @JustinasLelys Syntax is PHP 5.4 – COil Apr 14 '17 at 08:44
  • "username" can not be defined. So better check with "??" first. – Viktor Sydorenko Jul 11 '17 at 10:51
9

Inside a controller:

$request = $this->getRequest();
$username = $request->get('username');
Reinherd
  • 5,476
  • 7
  • 51
  • 88
  • 6
    In newer versions of Symfony, `$this->getRequest()` is deprecated, in favour of injecting the Request into the controller action, eg: `public function showAction(Request $request, $id);` – Adam Elsodaney Dec 04 '14 at 14:13
9

As now $this->getRequest() method is deprecated you need to inject Request object into your controller action like this:

public function someAction(Request $request)

after that you can use one of the following.

If you want to fetch POST data from request use following:

$request->request->get('var_name');

but if you want to fetch GET data from request use this:

$request->query->get('var_name');
Ashish Awasthi
  • 1,484
  • 1
  • 19
  • 34
9

Your options:

  1. Simple:
    • $request->request->get('param') ($_POST['param']) or
    • $request->query->get('param') ($_GET['param'])
  2. Good Symfony forms with all validation, value transormation and form rendering with errors and many other features:
  3. Something in between (see example below)
<?php
/**
 * @Route("/customers", name="customers")
 *
 * @param Request $request
 * @return Response
 */
public function index(Request $request)
{
    $optionsResolver = new OptionsResolver();
    $optionsResolver->setDefaults([
        'email' => '',
        'phone' => '',
    ]);
    $filter = $optionsResolver->resolve($request->query->all());

    /** @var CustomerRepository $customerRepository */
    $customerRepository = $this->getDoctrine()->getRepository('AppBundle:Customer');

    /** @var Customer[] $customers */
    $customers = $customerRepository->findFilteredCustomers($filter);

    return $this->render(':customers:index.html.twig', [
        'customers' => $customers,
        'filter' => $filter,
    ]);
}

More about OptionsResolver - http://symfony.com/doc/current/components/options_resolver.html

luchaninov
  • 6,792
  • 6
  • 60
  • 75
7

You can do it this:

$clientName = $request->request->get('appbundle_client')['clientName'];

Sometimes, when the attributes are protected, you can not have access to get the value for the common method of access:

(POST)

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

(GET)

$clientName = $request->query->get('clientName');

(GENERIC)

$clientName = $request->get('clientName');
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
Yoander
  • 71
  • 1
  • 1
3

Most of the cases like getting query string or form parameters are covered in answers above.

When working with raw data, like a raw JSON string in the body that you would like to give as an argument to json_decode(), the method Request::getContent() can be used.

$content = $request->getContent();

Additional useful informations on HTTP requests in Symfony can be found on the HttpFoundation package's documentation.

2

For symfony 4 users:

$query = $request->query->get('query');
Edmunds22
  • 715
  • 9
  • 10
1
$request = Request::createFromGlobals();
$getParameter = $request->get('getParameter');
Manuel M.
  • 19
  • 1
  • Is this still the way to go for functions that do not have the `Request` parameter? (e.g. in private functions of the controller class for example) – fritzmg Nov 28 '16 at 08:50
1
use Symfony\Component\HttpFoundation\Request;

public function indexAction(Request $request, $id) {

    $post = $request->request->all();

    $request->request->get('username');

}

Thanks , you can also use above code

Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28
Meet
  • 328
  • 3
  • 15
1

#www.example/register/admin

  /**
 * @Route("/register/{role}", name="app_register", methods={"GET"})
 */
public function register(Request $request, $role): Response
{
 echo $role ;
 }
0

If you need getting the value from a select, you can use:

$form->get('nameSelect')->getClientData();
0

Try this, it works

$this->request = $this->container->get('request_stack')->getCurrentRequest();

Regards

AchrafSoltani
  • 226
  • 1
  • 9
  • This does not answer the question at all. The person asking the question already hast access to the request object. – Layton Everson Dec 05 '14 at 18:54
  • 1
    @LaytonEverson sorry but you are mistaken, his method // $this->getRequest() is deprecated since 2.4, that's why it's not working, so he doesn't really have access to the request object ;) – AchrafSoltani Dec 06 '14 at 23:12
  • Although you are not wrong about that, asker is wondering what method retrieves a variables from the request object. @Cerad answered this question correct. Not only did he provide the correct way to access the Request object, he also answer the question question. – Layton Everson Dec 08 '14 at 16:15
0
public function indexAction(Request $request)
{
   $data = $request->get('corresponding_arg');
   // this also works
   $data1 = $request->query->get('corresponding_arg1');
}
abhinand
  • 554
  • 5
  • 10
  • 2
    While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. – Bono Apr 28 '16 at 12:17