URLs, links and routing
URLS
URLS
URL from route
use Drupal\Core\Url;
$url = Url::fromRoute($route_name, $params);
URL from URI
use Drupal\Core\Url;
$url = Url::fromUri('internal:/mypath/to/style.css');
Add options to an existing URL (classes, target, etc)
$url->setOptions([
'attributes' => [
'target' => '_blank',
],
]);
Links
Generate a link
$my_link = \Drupal::service('link_generator')->generate($text, Url $url);
OR
use Drupal\Core\Link;
$renderable_link = Link::fromTextAndUrl($text, Url $url);
Create a link from route (skip having to use Url class)
Link::createFromRoute($text, $route_name, ['arg1' => 'value'], ['attributes' => ['class' => 'use-ajax']]);
Convert above link to render array or link string
$link_render_array = $renderable_link->toRenderable();
$link_string = $renderable_link->toString();
Paths
Get the node from the current path
$node = \Drupal::routeMatch()->getParameter('node');
Get current path
$path = \Drupal::service('path.current')->getPath();
Get path arguments (from path above)
$path_args = explode('/', $path);
Get the current route
$route_name = \Drupal::service('current_route_match')->getRouteName();
Requests
Get the query parameter from a GET request
$name = \Drupal::request()->query->get('name');
Get the parameter from a POST request
$name = \Drupal::request()->request->get('name');
Get the host (ex: www.google.com)
$host = \Drupal::request()->getHost();
Redirect
use Symfony\Component\HttpFoundation\RedirectResponse;
new RedirectResponse(\Drupal::url($route_name));