Drupal 8 Url Tips. Get Name, Path, Args ...

Submitted by editor on Tue, 12/20/2016 - 10:26
Question

How to get Url Object From Path ?
How to get route data from Url Object?

 

Drupal 8 Url Object
use Drupal\Core\Url;

Create a Url

Create Url from route name

$url = Url::fromRoute('<current>');
$url = Url::fromRoute('entity.node.canonical', ['node' => 1], []);

//Get Path/Route from Url Object
$url = Url::fromRoute('entity.node.canonical', ['node' => 1], []);
if ($url->isRouted()) {
  $out = $url->toString(); // Get : /en/node/1
  $out = $url->getInternalPath(); // Get : node/1
  $out = $url->getRouteName(); // Get : entity.node.canonical
  $out = $url->getRouteParameters(); // Get : Array ([node] => 1)
  $out = $url->getOptions(); // Get : Array ()
}

Create a route from external Uri

Get Data from External Url Object
$url = Url::fromUri("http://www.drupal8.ovh/en/tutoriels/275/drupal-8-url-tips-get-name-path-args?test=yes");
if ($url->isExternal()) {
  $out = $url->toString();//Get : http://www.drupal8.ovh/en/tutoriels/275/drupal-8-url-tips-get-name-path-args?test=yes
  $out = $url->getOptions(); // Get : Array([external] => 1)
  $out = $url->getUri(); //Get : http://www.drupal8.ovh/en/tutoriels/275/drupal-8-url-tips-get-name-path-args?test=yes
}

Note : If you are not sure, its better to use try ant chtch to avoid exceptions.
try {
  $url->getUri();
}
catch (\Exception $e) {
  drupal_set_message("Has internam path : " . $url->toString());
}

Create a route from internal Uri

Example :
$url = Url::fromUserInput("/node/1");

//TODO : $url = Url::fromRouteMatch($route_match);

Get Url from path validator service.

Drupal has path validator service : PathValidatorInterface::getUrlIfValid()
\Drupal::service('path.validator')->getUrlIfValid('node/1');

 

 

Tags

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.