n How to create URLs Programmatically in Drupal 8 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Code snippet that can be used to create URLs Programmatically in Drupal 8.

 

// Internal path (defined by a route in Drupal 8).
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('The Carney Effect'), Url::fromUri('http://www.thecarneyeffect.co.uk/'))->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]),
);

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook