Andrew Fletcher published: 9 June 2021 (updated) 4 January 2022 1 minute read
Creating URL's in Drupal programmatically:
Internal path
use Drupal\Core\Link;
use Drupal\Core\Url;
$internal_link = Link::fromTextAndUrl(t('Drupal nodes'), Url::fromUri('internal:/node', $options))->toString();
External Url
use Drupal\Core\Link;
use Drupal\Core\Url;
$external_link = Link::fromTextAndUrl(t('Codebales'), Url::fromUri('http://www.codebales.com/'))->toString();
Url with options
use Drupal\Core\Link;
use Drupal\Core\Url;
$options = array(
'query' => ['type' => 'article', 'status' => 1],
'fragment' => 'article-list',
'attributes' => ['class' => ['btn', 'btn-mini']],
'absolute' => TRUE,
);
$link = Link::fromTextAndUrl(t('Drupal node articles'), Url::fromUri('internal:/node', $options))->toString();
Render type Link
use Drupal\Core\Url;
$render_array['link'] = array(
'#title' => $this->t('Link Text Goes Here!'),
'#type' => 'link',
'#url' => Url::fromRoute('entity.node.canonical', ['node' => 1]),
);