How to get $_POST and $_GET parameters in Drupal 10

Drupal 10 uses the HttpFoundation component from the Symfony framework to handle HTTP requests, so accessing parameters from $_POST and $_GET is done differently than in previous versions of Drupal. In this blog post, we will look at how to get $_POST and $_GET parameters in Drupal 10.

First, let's take a look at how to get $_POST parameters in a custom controller. In a controller, you can get the current request with a type-hinted argument Request $request:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;

class ExampleController extends ControllerBase {

  /**
   * Controller to return a POST or a GET parameter.
   */
  public function action(Request $request) {

    // get your POST parameter
    $foo = $request->request->get('foo');

    return [
      '#plain_text' => $foo,
    ];
  }

}

In the example above, we use the $request->request->get() method to get the value of a POST parameter. Note that we are using '#plain_text' to escape the input data for HTML output.

Now, let's look at how to get $_GET parameters in a custom controller. Inject the RequestStack into your controller and then get the current request with the getCurrentRequest() method:

namespace Drupal\example_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * An example controller.
 */
class ExampleController extends ControllerBase {

  /**
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  private $requestStack;

  /**
   * Constructor.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('request_stack')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function action() {
    // Get your GET parameter here.
    $this->requestStack->getCurrentRequest()->query->get('foo');
  }

}

In the example above, we use the $this->requestStack->getCurrentRequest()->query->get() method to get the value of a GET parameter.

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!