78

In symfony 2 controllers, every time I want to get a value from post I need to run:

$this->getRequest()->get('value1');
$this->getRequest()->get('value2');

Is there any way to consolidate these into one statement that would return an array? Something like Zend's getParams()?

j0k
  • 22,600
  • 28
  • 79
  • 90
ContextSwitch
  • 2,830
  • 6
  • 35
  • 51

5 Answers5

166

You can do $this->getRequest()->query->all(); to get all GET params and $this->getRequest()->request->all(); to get all POST params.

So in your case:

$params = $this->getRequest()->request->all();
$params['value1'];
$params['value2'];

For more info about the Request class, see http://api.symfony.com/2.8/Symfony/Component/HttpFoundation/Request.html

Matt
  • 74,352
  • 26
  • 153
  • 180
Guillaume Flandre
  • 8,936
  • 8
  • 46
  • 54
  • 7
    To get values for parameters in the path (eg /posts/{id}) use `$request->attributes->all()`. I was using `$request->get()` thinking that was the only way to get this data and came here looking for another way. – Dreen Jan 13 '14 at 12:15
12

With Recent Symfony 2.6+ versions as a best practice Request is passed as an argument with action in that case you won't need to explicitly call $this->getRequest(), but rather call $request->request->all()

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;

    class SampleController extends Controller
    {


        public function indexAction(Request $request) {

           var_dump($request->request->all());
        }

    }
Aftab Naveed
  • 3,652
  • 3
  • 26
  • 40
3

Since you are in a controller, the action method is given a Request parameter.

You can access all POST data with $request->request->all();. This returns a key-value pair array.

When using GET requests you access data using $request->query->all();

lfurini
  • 3,729
  • 4
  • 30
  • 48
ckkaqa
  • 171
  • 1
  • 8
3

For Symfony 3.4, you can access the data for both GET and POST, Like This

Post:

$data = $this->request->request->all();

Get:

$data = $this->request->query->all();
Bibhudatta Sahoo
  • 4,808
  • 2
  • 27
  • 51
0

Well, remember this is always PHP, so you could just check for the superglobal variable $_REQUEST

https://www.php.net/manual/en/reserved.variables.request.php

ordinov
  • 69
  • 2
  • 2