Link field title from entity/route I have a Drupal link field configured to allow both internal and external links and have the title field enabled, but optional. 



I want users to be able to reference internal entities without having to specify anything in separate title field, and have the Link field's title pulled from the entity label.  However it appears that when the field's internal title value is left null, Drupal ends up using the field's uri value as the link title. This behavior seems odd to me. 

My question is this: given an internal uri value that looks like: entity:node/3500 how can I preprocess or alter the functionality of the Link field to load in the entity's title/label as the  title when it is left empty by the content editors.

I've searched for issues on drupal.org but didn't turn up much of anything useful. I found Get title from Route, which seems to recommend using the TitleResolver, but that depends on putting together a $request object, which seems extremely impractical.

Suggestions?
So, I've written a preprocess function to do this:

/**
 * Prepares variables for link fields.
 */
function mymoduleortheme_preprocess_field__link(&amp;$variables) {

  // If the link is a reference to an internal entity and there was no
  // link title provided by the content editor, then use the entity
  // label as the link text.
  $i = 0;
  foreach ($variables['element']['#items'] as &amp;$item) {
    if (empty($item-&gt;get('title')-&gt;getValue()) &amp;&amp; $item-&gt;getUrl()-&gt;isRouted()) {
      $parameters = $item-&gt;getUrl()-&gt;getRouteParameters();
      if (!empty($parameters)) {
        foreach($parameters as $entity_type =&gt; $id) {
          if ($entity = \Drupal::entityTypeManager()-&gt;getStorage($entity_type)-&gt;load($id)) {
            $variables['items'][$i]['content']['#title'] = $entity-&gt;label();
            break;
          }
        }
      }
    }
    $i++;
  }
}


This is working with both the standard Link field formatter as well as the "Separate link text and URL" formatter provided by Drupal 8 core.



My only doubt here is that I'm not sure how safe it is to assume getRouteParameters() will always be keyed with an entity type name and a value of the entity id.

Would appreciate your help to review and vet this. Thanks!