0

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?

2

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.

1
  • 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.
    – 4k4
    Nov 24 at 12:42

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.