2

I have to render a field of a node that is inside a content type in Drupal 8.

I have a content type called summary that has a field, called field_content that is an Entity reference field for unlimited items of a specific content type (article)

I'm able to get the current node and handle the field_content, but I cant access each of referenced items inside of this type.

Also I have tried to debug the field_content with kint but the browser crashes (I suppose that it happens becasue the data dump is very big) and I can't access the inner properties (I have to get a field called field_desc_text inside each article).

I need the node or the nid to load it of each of this inner items.

This is what i've tried:

       $currentNode = \Drupal::routeMatch()->getParameter('node');
    foreach ($currentNode->get('field_content') as $nodeRef)
    {
      kint($nodeRef); //*This debugs the entire referenced node, but there is no sight of my desired fields
      die;
     // kint($nodeRef[0]); *Cannot use object of type Drupal\\Core\\Field\\Plugin\\Field\\FieldType\\EntityReferenceItem as array
     // kint($nodeRef->get('title')); *Uncaught PHP Exception InvalidArgumentException: "Property title is unknown."

     die;

    }

And this is the output of the kint($currentNode):

https://mega.nz/#!Fogx0LpC!CYvc6YSRs1ZcgOAc4RCfDo5iVqjBLYckvuFEUgqRGx8

Thanks in advance!

1

1 Answer 1

3

You can access the entities referenced by an entity reference field using the following code.

$currentNode = \Drupal::routeMatch()->getParameter('node');
$entities = $currentNode->get('field_content')->referencedEntities();

The value returned from referencedEntities() is an array of objects that implement EntityInterface.
See the documentation and the code used by EntityReferenceFieldItemList::referencedEntities() for more details.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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