Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

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

By editor , 20 December, 2016
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');

 

Get data from current request

From a form, or a controller with requestStack
$host = $this->getRequest()->getSchemeAndHttpHost();

From static method:
$host : \Drupal::request()->getSchemeAndHttpHost();

Tags

  • Drupal 8
  • Code
Get args from URL in Drupal 8
Get node from url
Get the current page URI on Drupal 8

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer