How to get query parameter in Drupal 8?

Member

by darion , in category: PHP Frameworks , 2 years ago

How to get query parameter in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by giovanny.lueilwitz , a year ago

@darion 

In Drupal 8, you can use the Drupal::request() service to get the current request object and then use its getQueryString() method to retrieve the query string of the request. You can then parse the query string to get the individual query parameters.


Here is an example of how you can get a specific query parameter in Drupal 8:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use SymfonyComponentHttpFoundationRequest;

// Get the current request object.
$request = Drupal::request();

// Get the query string of the request.
$query_string = $request->getQueryString();

// Parse the query string to get the individual query parameters.
parse_str($query_string, $query_params);

// Get a specific query parameter.
$param = $query_params['param_name'];


Alternatively, you can use the get() method of the request object to directly get a specific query parameter by name:

1
$param = $request->query->get('param_name');


This method will return the value of the param_name query parameter if it exists, or null if it does not.


You can also use the Drupal::routeMatch() service to get the route match object, which contains the raw values of the route parameters. You can then use the getRawParameters() method of the route match object to get an array of all the route parameters, including query parameters.


For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use DrupalCoreRoutingRouteMatchInterface;

// Get the route match object.
$route_match = Drupal::routeMatch();

// Get the raw route parameters.
$parameters = $route_match->getRawParameters();

// Get a specific query parameter.
$param = $parameters->get('param_name');


by filiberto , 5 months ago

@darion 

Please note that the code examples provided assume that you are in a context where you have access to the Drupal service container (e.g., a custom module or theme file). If you are in a class that extends a Drupal core class (e.g., a controller), you can directly inject the necessary services (e.g., RequestStack or RouteMatchInterface) and use them accordingly.