I am using the following code.

$url = Url::fromUri('javascript:', array('external' => true));
$link = Link::fromTextAndUrl(t("#action"), $url)->toString();

It causes the following error:

InvalidArgumentException: The URI 'javascript' is invalid. You must use a valid URI scheme. in Drupal\Core\Url::fromUri() (line 280 of C:\xampp\htdocs\drupal826\core\lib\Drupal\Core\Url.php).

Is this supported in Drupal 8?

I found How to create an EMPTY anchor-only link with l()? but that is for Drupal 7.

  • Did you add the use statements at the top of your code? use Drupal\Core\Url; and use Drupal\Core\Link; ? – No Sssweat Feb 28 '17 at 8:03
  • yes added both use Drupal\Core\Link; use Drupal\Core\Url; – rjD Feb 28 '17 at 9:37
  • If you read the public static function Url::fromUri, there is no such thing as external, I think you're looking for fragment and also javascript: is not a URI. – No Sssweat Feb 28 '17 at 9:45
  • I want the final result to be like this:<a href="javascript:;">#link</a> – rjD Feb 28 '17 at 9:52
  • I don't think you can, why do you need javascript:; there anyways? – No Sssweat Feb 28 '17 at 23:18

So we create url for link which should be empty.

For this we can use ::fromUserInput() and send parameters starting with # or /.

Or create url from route ::fromRoute('<none>') with specific token.

$url = Url::fromUserInput('#');

Way to create link is usual for D8:

$link = Link::fromTextAndUrl($this->t('Some link'), $url);

| improve this answer | |
  • 1
    Did you got any errors? – Maxim Ivanov Apr 4 '17 at 11:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.