Creating links and URLs in Drupal
The Drupal\Core\Url class is a great utility for generating URLs and redirecting to specific routes. In addition to the ::fromRoute() method , this class provides a number of other useful static methods. Below, we'll take a look at and overview of the key static methods and how they can be used.
Url::fromUri()
This method is used to create a URL object from a "URI" string, such as an external URL or a custom internal URL.
Example of use:
// External URL
$url = Url::fromUri('https://www.google.com');
// Internal URL with query parameters
$url = Url::fromUri('internal:/node/60', ['query' => ['key' => 'value']]);
// Custom scheme
$url = Url::fromUri('base:/my-personal-page');
Url::fromUserInput()
This method is used to create a URL based on user input. It accepts a relative path that users can enter into the browser and resolves it into a URL object.
Example of use:
$url = Url::fromUserInput('/my-personal-page');
// Adding query parameters
$url = Url::fromUserInput('/my-personal-page', ['query' => ['filter' => 'active']]);
Url::fromInternalUri()
Creates a URL object from an internal URI, specifically used when working within Drupal's internal routes.
Example of use:
$url = Url::fromInternalUri('node/60');
// Internal URI with options
$url = Url::fromInternalUri('node/60', ['absolute' => TRUE]);
Url::fromString()
This method is used to create a URL object from a path or string-based URL.
Example of use:
// Creating from a string path
$url = Url::fromString('/user/login');
// Including query parameters
$url = Url::fromString('/node/999', ['query' => ['destination' => 'home']]);
Url::fromRouteMatch()
This method creates a URL object from the current RouteMatch object, which is useful when working with the routing system in controllers.
Example of use:
// Get the current route match (usually done within a controller)
$route_match = \Drupal::routeMatch();
// Create a URL object from the route match
$url = Url::fromRouteMatch($route_match);
Common parameters in the $options array
When creating a URL object in Drupal using the fromRoute() , fromUri() , or other methods , the $options array allows you to pass additional parameters that modify the behavior of the generated URL. Common options that can be passed are:
- absolute : If TRUE, generates an absolute URL. If FALSE (default), generates a relative URL.
- query : An array of query string parameters to add to the URL.
- fragment : Adds a fragment identifier to the URL (e.g. #section1)
- language : A LanguageInterface object to generate the URL in a specific language.
- https : Forces the scheme to HTTPS if set to TRUE. This option is deprecated in modern Drupal as HTTPS must be handled at the server level.
- base_url : A base URL to use instead of the default.
- prefix : Adds a path prefix (such as a language prefix or a site section prefix).
- entity_type and entity : To generate URLs based on entities.
Some examples
Now let's show some examples putting into practice everything seen up to this point!
In this first example we are going to generate a URL for a route, add query parameters, make it absolute, and add a fragment identifier.
// Generate a URL to a specific route with options.
$options = [
'absolute' => TRUE, // Make the URL absolute
'query' => ['page' => 1, 'category' => 'food'], // Add query parameters
'fragment' => 'comments', // Add a fragment identifier
];
// Create a URL to the 'entity.node.canonical' route for node 96.
$url = Url::fromRoute('entity.node.canonical', ['node' => 96], $options);
// Convert the Url object to a string.
$url_string = $url->toString();
The generated URL would be the following: http://www.my-web.com/node/96?page=1&category=food#comments
In the following example we are going to build a URL with options using Url::fromUri() .
// Generate an external URL with query parameters and absolute URL option.
$options = [
'absolute' => TRUE, // Generate an absolute URL
'query' => ['ref' => 'newsletter'], // Add query parameters
'fragment' => 'subscribe', // Add fragment identifier
];
$url = Url::fromUri('https://www.personal-web.com/subscribe', $options);
// Convert to a string.
$url_string = $url->toString();
The generated URL would be the following: https://www.personal-web.com/subscribe?ref=newsletter#subscribe
Display URL in a Twig template
It is possible to pass URLs and links to a Twig template. In the following use case, we are going to pass a link from the controller and render it from a Twig template.
Controlador (mymodule/src/Controller/SampleController.php):
public function myPage() {
$url = Url::fromRoute('entity.node.canonical', ['node' => 1]);
$link = Link::fromTextAndUrl('Go to Node 1', $url);
return [
'#theme' => 'my_template',
'#my_link' => $link->toRenderable(),
];
}
Plantilla Twig (mytheme/templates/mytemplate.html.twig):
<div>
{{ my_link }}
</div>
And you, how do you use URLs in Drupal?