LC
php
Back to Snippets

Drupal Create Links Programmatically

Create various types of links in Drupal 8 using URL and Link classes.

drupallinksroutingtheming
php
      use Drupal\Core\Url;
use Drupal\Core\Link;

// Link to a node
$url = Url::fromRoute('entity.node.canonical', ['node' => 1]);
$link = Link::fromTextAndUrl('My Link', $url)->toString();

// External link
$url = Url::fromUri('https://example.com');
$link = Link::fromTextAndUrl('External', $url)->toString();

// Link with classes
$url = Url::fromRoute('entity.node.canonical', ['node' => 1]);
$url->setOption('attributes', ['class' => ['btn', 'btn-primary']]);
$link = Link::fromTextAndUrl('Styled Link', $url)->toString();

// Link with query string
$url = Url::fromRoute('view.search.page', [], [
    'query' => ['keyword' => 'test'],
]);

// Absolute URL
$url = Url::fromRoute('entity.node.canonical', ['node' => 1], [
    'absolute' => TRUE,
]);

// Taxonomy term link
$url = Url::fromRoute('entity.taxonomy_term.canonical', [
    'taxonomy_term' => $tid,
]);

// Edit page link
$url = Url::fromRoute('entity.node.edit_form', ['node' => $nid]);