2

I am creating LinkedImage field, formatter and widget so that images can be linked to somewhere.

And I have an issue with the input. The user can set internal or external links like /node/1, <front> or http://www.google.com. But the Url object that is required for link render element has no method that would work with all of these.

The Url::fromUserInput will work with internal paths but not with <front>. The Url::fromUri() will work with http://www.google.com but not with <front> or /node/1.

So I had to implement logic to distinguish the format and also I had to add validation handler into the widget telling the user that the link has to start with forward slash or with http prefix.

But I do not like this approach. Seems like this is not how it is supposed to be done.

So how can I properly construct Url object from these three types of input?

Also another issue here is that if "malformed" URL is already set (ie. it hasn't been validated via my UI validation handler) then I will get WSOD and that is just really bad UX.

Plus, as you can see, <front> is not working with any of these methods whic hrequires additional logic.

1

I had the same problem, so please try this:

$url_object = \Drupal::service('path.validator')->getUrlIfValid($path);
$url_object->setAbsolute();
$url = $url_object->toString();
  • Seems to be working. Although links starting with www instead of http will return false. But I'm fine with that + I am using textfield ant not url since it does not work with internal paths ans so i have custom validation handler in place which ca ntake care of this. – user21641 Oct 23 '15 at 11:18

Your Answer

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