I need to slightly modify some URLs that are in a "Link" field on a custom entity type.

In a mytheme_preprocess_myentity I've found that field with $variables['elements']['field_my_url'][0] I get this output in Kint

enter image description here

I've tried using a number of methods on the #url object but I don't think I'm doing it correctly... I'm just confused on how to modify it at this point.

How can I change the external URL to which this particular field is pointing?

1 Answer 1


Drupal's Core Url has a static fromUri() method (see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AfromUri/8.2.x)

With that in mind you should be able to swap out the ['#url'] with a new one thusly:

...['#url'] = \Drupal\Core\Url::fromUri('externalURL');

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.