5

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.

6
  • 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, 2017 at 8:03
  • yes added both use Drupal\Core\Link; use Drupal\Core\Url;
    – rjD
    Feb 28, 2017 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, 2017 at 9:45
  • I want the final result to be like this:<a href="javascript:;">#link</a>
    – rjD
    Feb 28, 2017 at 9:52
  • I don't think you can, why do you need javascript:; there anyways?
    – No Sssweat
    Feb 28, 2017 at 23:18

2 Answers 2

4

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);

2
  • 1
    Did you got any errors? Apr 4, 2017 at 11:40
  • Url::fromUserInput('#') does not work. It does create an "empty" link, but the goal is to get a link with href="#", which is not the result.
    – mbomb007
    Apr 12, 2023 at 13:20
0

The best way I've found is this:

use Drupal\Core\Template\Attribute;

// A value that would inject HTML if you just used string interpolation.
$value_needing_sanitize = '"><h1>BAD</h1><a href="#" class="';

// Optionally add attributes with any HTML sanitized.
$attributes = new Attribute([
  'data-input' => $value_needing_sanitize,
]);

// Create the anchor tag.
$link = <<<HTML
  <a href="#" $attributes>
HTML . $this->t('Click here') . '</a></span>';

// Render array
$render_array = ['#markup' => $link];

If you don't need any attributes set to user input, then you can remove those parts and just create the anchor tag and render array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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