nortmas
9/27/2017 - 4:48 PM

Url & Path & Args

<?php

use Drupal\Core\Url;
use Drupal\Core\Link;

\Drupal::linkGenerator()->generate($title, $url);

 // Or if you need to pass spectial chars like &shy; or any HTML tag in your link title you can also use the following:
$link_text = Markup::create('<div>' . $node->getTitle() . '</div>');
$link = Link::fromTextAndUrl($link_text, $node->toUrl());

$url = Url::fromUserInput('/node/12');

$route_parameters = ['uid' => $uid];
$route_options = ['query' => ['destination' => $destination]];
$url = Url::fromRoute('acc_questionnaire.share_product_form', $route_parameters, $route_options);
// or
$login_link = Url::fromRoute('user.login', ['destination' => $destination])->toString();

$url = Url::fromUri('http://example.com', ['attributes' => ['target' => '_blank'])->toString();
//or
$url = Url::fromUri('internal:/node/123', ['absolute' => TRUE])->toRenderable();

$link = Link::fromTextAndUrl(t('label'), $url)->toString();

// Retun node/123
$url = Url::fromUri('internal:/node/123')->getInternalPath();

# <nolink>, <front>
Url::fromRoute('<none>', []);
<?php

/**
 * Get an entity url
 */
Url::fromRoute('entity.commerce_product.canonical', ['commerce_product' => $product->id()])->toString();

$url = Url::fromRoute('entity.node.edit_form', array('node' => NID));
$link = Link::fromTextAndUrl(t('Open Project'), $url);
$link = $project_link->toRenderable();


/**
 * Get the current path
 */
$current_url = Url::fromRoute('<current>');

// Get full current path including GETrams.
$current_path = \Drupal::request()->getRequestUri();

# to get the current path
$current_path = \Drupal::service('path.current')->getPath();   

#to get current path query args
\Drupal::request()->query->all();

# get a route obj from url
$obj_route = \Drupal::service('path.validator')->getUrlIfValid('blog');  
# get a route name from rote obj
$route_name = $obj_route->getRouteName();                                

# Create a link.  <front>, <none>, <nolink>  - are possible instead of $route_name
Link::createFromRoute(t('Home'), $route_name);   

# args for current path
$path_args = array_values(array_filter(explode('/', \Drupal::service('path.current')->getPath()))); 
# args for current alias
$path_args = array_values(array_filter(explode('/', \Drupal::request()->getRequestUri())));