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?

1 Answer 1


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

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

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

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 */

/* success */

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

  • 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.
    – 4uk4
    Nov 24, 2021 at 12:42

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.