Drupal - How do I create a route with a query string?

You cannot create a route based on the query string, but you still can retrieve query string values in your code:

amu_hal.publicationsPerYear:
  path: '/publications/{year}'
  defaults:
    _controller: '\Drupal\amu_hal\Controller\AmuHalController::publicationPerYear'
    _title: 'publicationPerYear'
    year: 2016
  requirements:
    _permission: 'access content'
public function publicationPerYear($year) {
  $url = \Drupal::request()->query->get('url') ?: 'default';
}

I don't think we support passing a query argument through like that.

Just get the request object with Request $request and then get the url from there with $request->query->get('url');


Sample method

  /**
   * @param \Symfony\Component\HttpFoundation\Request $request
   */
  public function download(Request $request) {
    dd($request->query->get('url'));
  }

Meanwhile (Drupal 8.6) it's possible to declare query parameters in drupal routes. In a mymodule.routing.yml file, to declare a query variable "token", do it like this:

mymodule.mailcommitter:
  path: '/mailcheck/{uid}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ProfilController::checkMailCommit'
    _title: 'commit mail'
  options:
      query:
        token: ""
  requirements:
    _permission: 'access content'

Then, you build an url by route like so

'url' => Url::fromRoute('mymodule.mailcommitter', ['uid' => 1], ['query' => ['token' => 'hello']])

The result is an uri like /mailcheck/1/?token=hello

Also check this doc: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-routes

Tags:

Routes

8