Work with links in Drupal

Work with links in Drupal

In Drupal it is not so easy just to get a node link.

Below I provide some examples how get a link for different cases.

First, it is most usual way just to get a node link:

<?php

use Drupal\Core\Url;

$nid = 123;

$link = Url::fromRoute('entity.node.canonical', ['node' => $nid])->toString();

dump($link);

So, this code will return link like "/node/1" or alias like "/some-node-alias" if module "Path" is enabled.

But, if you need to get a link with markup you should use next code:

<?php

use Drupal\Core\Link;

$nid = 123;

$link = Link::fromTextAndUrl(t('A node link'), Url::fromRoute('entity.node.canonical', ['node' => $nid]))->toString();

dump($link);

Well, this code will return link like this:

<a href="/node/1">A node link</a>

Also, you can create renderable array to some manipulation like add particular class or so:

<?php

use Drupal\Core\Url;

$nid = 123;

$link = Url::fromRoute('entity.node.canonical', ['node' => $nid])->toRenderable();

dump($link);

And sometimes we have to get a node by alias, so it is possible by code below:

<?php

use Drupal\node\Entity\Node;

$node_alias = '/some-node-alias';

$url = \Drupal::service('path.validator')->getUrlIfValid($node_alias);

// Check if it is a correct alias.
if ($url) {
  $parameters = $url->getrouteParameters();

  // Check if it is a node alias.
  if (isset($parameters['node'])) {
      $node = Node::load($parameters['node']);
      dump($node);
    }
}

By the way method "fromRoute" of class "Url" can use specific options and you can get a link with full URL:

<?php

use Drupal\Core\Url;

$nid = 123;

$link = Url::fromRoute('entity.node.canonical', ['node' => $nid], ['absolute' => TRUE])->toString();

dump($link);

This code will return URL like this — "https://example.com/node/123".

And a couple tips below:

You will get a link to homepage like "/homepage" if you use this code:

<?php

use Drupal\Core\Url;

$link = Url::fromRoute('<front>')->toString();

dump($link);

You will get a link to current page like "/current-url" if you use this code:

<?php

use Drupal\Core\Url;

$link = Url::fromRoute('<current>')->toString();

dump($link);

Well, it is a way create an empty link with GET params like this "?order=id&sort=desc":

<?php

use Drupal\Core\Url;

$link = Url::fromRoute('<none>', [], ['query' => ['order' => 'id', 'sort' => 'desc']])->toString();

dump($link);

Also, it is possible to get an url of any entity (if this entity has URL) like "Views":

<?php

use Drupal\Core\Url;

$link = Url::fromRoute('view.frontpage.page_1')->toString();

dump($link);

Basically, that is it.

If you wish you can have a deeper look into "Drupal\Core\Url" class and find methods like "fromUri", "fromEntityUri", "fromUserInput" and so on and so forth.