Get Link value in Media entity We have a Media type called Documents that has a Link field called field_link. We need to obtain the URL (external or internal) from the field so that we can use to wrap block elements inside of a &lt;a&gt; tag in our twig templates. All works fine when the link is an external URL, but when linking to an internal page, the following code does not work in our mymodule_preprocess_media hook. 

How can I obtain both the internal and external link within the field_link field inside of the mymodule_preprocess_media hook?

This is what we have tried, but only works for external links.

function mymodule_preprocess_media(&amp;$variables) {
  $media_entity = $variables['elements']['#media'];
  $link = $media_entity-&gt;get('field_link')-&gt;first();

  // This works for external, but not internal
  $link_value = $link-&gt;getUrl()-&gt;getUri();

  $variables['custom_var'] = [
    'link_value' =&gt; $link_value,
  ];
}


media--document.html.twig

&lt;a href="{{ custom_var['link_value'] }}"&gt;
  &lt;div&gt;{{ name }}&lt;/div&gt;
&lt;/a&gt;


When using ksm($link-&gt;getUrl()), we find that the uri value is NULL when the link is internal. 

Goals:


Get the internal link (absolute) using hook_preprocess_media
Get the external link using hook_preprocess_media
Try the following:

/**
 * Implements hook_preprocess_media().
 */
function mymodule_preprocess_media(&amp;$variables) {
  $media_entity = $variables['elements']['#media'];
  /**
   * @note: in case your field not multiple, otherwise loop through the field.
   */
  $link = $media_entity-&gt;get('field_link')-&gt;first();
  if ($link-&gt;isExternal()) {
    //- External.
    $link_value = $link-&gt;getValue()['uri'];
  }
  else {
    //- internal.
    $link_value = $link-&gt;getUrl()-&gt;toString();
  }
  $variables['custom_var'] = [
    'link_value' =&gt; $link_value,
  ];
}