1

How can I generate a link in a proper way in Drupal 8? I have a field where the user can say an internal or external page/website.

Internal:
/node/6
/articles
/articles#Subheading
etc.

External:
www.google.com
//www.google.com
https://www.google.com

How can I transform these into a link with the following condition:
the site root is: www.mydomain.com/mysite/
internal links should have language versions: i.e. en/articles or pt/articles .

I've tried with Link::fromTextAndUrl('My link', Url::fromUri('internal:/articles')), but this requires a URI which is not my goal and it doesn't follow the selected user language.

  • Why aren't you using core link field? – Hudri Jan 23 at 15:54
  • This data is saved into config. (as a module's config) – golddragon007 Jan 23 at 15:56
1

You do not need internal:/ you just need to have some help text that says an internal path should begin with a slash.

After that, when you create the links, you can do:

use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Component\Utility\UrlHelper;

....
....
....

function or method.... {
  $path = // get config value
  $label = // get config value

  if (UrlHelper::isExternal($path)) {
    $url = Url::fromUri($path);
  } else {
    $url = Url::fromUserInput($path);
  }

  return Link::fromTextAndUrl($label, $url);
}

Of course I am assuming there is always a value... you'd have to add your own checks so you don't get errors calling Url:: for null or empty input, etc.

The return will be an renderable array to use. I am using a similar method to allow input for third party settings on a config entity. This way the value can be internal or external.

| improve this answer | |
  • I don't know why but this does not follow the selected site language. I hope not because I'm using the Link::fromTextAndUrl(..., ...)->toString() function... – golddragon007 Jan 23 at 16:31
  • I don't work with languages much, but it seems like either the link needs to have the langcode in it: drupal.org/project/language_hierarchy/issues/3088151 but there appears to be a core issue as well drupal.org/project/drupal/issues/2924653 – Kevin Jan 23 at 16:37
  • Well, the interesting part is if I generate it from the route it has language code in the URL. But from a string, it's not really want to generate a language code in it... which is a problem. Another interesting thing, if I use node/nid then there will be language code in the URL, but it won't be alias... If I use the alias, then there won't be language code in the URL... – golddragon007 Jan 23 at 17:11
  • Actually it worked fine, but I didn't have some translation for some languages and that's why I had problems, between reality and the expectations... – golddragon007 Mar 5 at 12:26

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.