Score:1

How can I retrieve information about the current request's URL?

us flag

I need help finding a way to get the current request URL in a controller and, based on that, change the webform name in the controller.

My code:

'#url' => Url::fromRoute('entity.webform.canonical',['webform' => 'form1'])

In this line of code, how can I switch between form1 or form2 based on whether the request URL contains a particular path?

Score:3
cn flag

I need help finding a way to get the current request URL in a controller

In a controller get the request with a type-hinted argument Request $request:

<?php

namespace Drupal\mymodule\Controller;

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

class ExampleController extends ControllerBase {

  /**
   * Controller to return a link to a webform.
   */
  public function action(Request $request) {

    // calculate $webform with $request->getPathInfo()

    return [
      '#type' => 'link',
      '#title' => 'Foo',
      '#url' => Url::fromRoute('entity.webform.canonical', ['webform' => $webform]),
      '#cache' => ['contexts' => ['url.path']],
    ];
  }

}

You can get other information from the request, but then you need to adjust the cache context(s). See for example https://drupal.stackexchange.com/a/245597/47547

leymannx avatar
ne flag
You don't need to inject it?
4uk4 avatar
cn flag
No, this is the most basic usage of a controller receiving a request and returning a response.
Score:1
cn flag

URL info is available from the request_stack service. In procedural code getting the URL looks like this:

$url = \Drupal::request()->getRequestUri();

There's also a helper to get query parameters if you need them, e.g.

if (!empty(\Drupal::request()->query->get('foo'))) {
  
}

In your case you should inject the request_stack service into your controller, and get the request object from its getCurrentRequest() method (rather than getting it from \Drupal::request() directly).

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.