Score:0

How get the referenced entity inside a field link?

br flag

I'm on D9. I've a paragraph with a Link field. I need to get the referenced entity programmatically.

What I've managed so far is:

       $nid = NULL;
       $field_link = $paragraph->get('field_link')->first();
       $route_params = $field_link->getUrl()->getRouteParameters();
        
        if(isset($route_params['node'])) {
          $nid = $route_params['node'];
        }

       if($nid) {
               ....
       }

But looks quite convoluted to me - and rely on the fact that the entity linked is only of type 'node'. Isn't there some function that provide the data directly\ in a more robust way?

Score:2
ru flag

I am currently using this code for a very similar task:

/** @var $link \Drupal\Core\Url */
if (!$link->isRouted()) {
  /* internal unrouted or external link */
  return;
}

$route = $link->getRouteParameters();
$entityType = key($route);
$referencedEntity = NULL;
try {
  $referencedEntity = \Drupal::entityTypeManager()
    ->getStorage($entityType)
    ->load($route[$entityType]);
  $referencedEntity = \Drupal::service('entity.repository')
    ->getTranslationFromContext($referencedEntity);
}
catch (Throwable $t) {
  /* Don't know if this is necessary, but I don't know what is coming out of getRouteParameters() */
  return;
}

if (!($referencedEntity instanceof \Drupal\Core\Entity\ContentEntityBase)) {
  /* maybe you want to allow different kind of entities here, e.g. a webform is no content entity */
  return;
}

/* success */
doStuff($referencedEntity);

Basically the same you are already doing, but you can use the key to get the entity type and make it more generic.

4uk4 avatar
cn flag
Great code example. To make it more predictable what is in getRouteParameters() I would check first getRouteName() for a pattern like `entity.ENTITY_TYPE.canonical`.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.