How do you capture an entity reference field "ex: related book" and use its values (title, image, body) in a single node twig template?

Comments

nolfranklin’s picture

I managed to pull basic values when setting the display format of the entity reference to "rendered entity" but no luck yet grabbing the related image.

Within the singular node:

ex: {{ content.related_book[0]['#node'].field_book_title[0].value }} properly displays the related node's field but {{ content.related_book[0]['#node'].field_book_cover_image[0].value }}, with and without ".value" comes up empty when requesting an image.

neha.gangwar’s picture

Any solution you get for this.. Please share.

neha.gangwar’s picture

And added required image in that view mode. Referencing this field in another content type as 'rendered entity' in manage display. and simply render the {{ content.field_book_image }} in my twig template. It Works :)

Jeff Burnz’s picture

How are you hiding the output of the reference field?

I can see this will work, but how to print multiple fields and what if the reference content is the same content-type?

I've messed with this for about half and hour and still finding a way to do this in code :/

ashish.ietecs’s picture

For hiding a particular field from content you should use like below code in your respective twig template -

{{ content|without('field_name') }}

If you have multiple values in reference field then you can print all the values like below -

{{ content.field_name[0]}}
{% for key, value in content.field_name %}
   {% if key > 0 %}
        {{ ' | ' }}
         {{ value }}
   {% endif %}
{% endfor %}   

In above code i have concatenated value with '|'. You can apply your logic for the presentation of field values in for loop.

Note - field_name is placeholder for field. You have to replace it with your field name. You can use "kint" {{ kint(content) }} module which is available in Drupal8 devel module.

Thanks

Jeff Burnz’s picture

neha.gangwar is using a View mode and then accessing the referenced entities fields directly, i.e.:

{{ content.field_image }}

If you try to use the without() filter or Hidden in the Display Settings you can no longer access the referenced content fields in the same way - so to be blunt, using without() doesn't work in this situation.

I wonder if he's not printing {{ content }} at all?

Note - I think themers should be careful about directly accessing items e.g. {{ content.field_image[0] }} because this bypasses theme and will print without template and any html field wrappers - fine if that's what you want, but could result in layout or style issues.

webdevfreak’s picture

This solution is helpful and worked fine for me.
 

{{ content.field_name[0]}}
{% for key, value in content.field_name %}
   {% if key > 0 %}
        {{ ' | ' }}
         {{ value }}
   {% endif %}
{% endfor %}  
ashique12009’s picture

This is working good but in my case it is making a dropdown in my TWIG file output.
Can get the dropdown value only loop through?

{{ product.variations[0] }}

              {% for key, item in product.variations %}

                {% if key > 0 %}

                  {{ ' | ' }}

                  {{ item.value }}

                {% endif %}

              {% endfor %} 

Thanks

baptisten’s picture

You can also use available methods.
I accessed all fields through {{content.ENT_REFERENCE[0]['#node'].getTitle()}}. You also have getFields() and some others.

dkre’s picture

@baptisten. Thank you!

bkosborne’s picture

I think a problem with this approach is that you're not running field formatted on the field, you're just accessing the data from the entity object directly. This is fine for simple field types like a title, but if you're accessing a text field that's meant to be filtered on output, it's more complicated. I think in this case the only approach is to manually pass the raw text data into the filter formatter in the node preprocess function and use it in the template.

tsubeta’s picture

I always have the same issue, dunno why bro

nehapandya55’s picture

We can render label of entity reference field using below line of code

{{ contnet.field_medicine_name.entity.title.value  }}

i have used it in node template.

bkudrle’s picture

For me, I had to use the node as the base reference, the content did not work. So in this example, I would use...

{{ node.field_medicine_name.entity.title.value }}

I replaced 'title' with whatever field in the referenced entity that I was trying to display, and that worked for me. If there were multiple references, then it would use an array reference, as in this example...

{{ node.field_medicine_name[0].entity.title.value }}

I was also using this in a node template.

Mukeysh’s picture

How can we get node title with a link? I am only able to get node title by using this node.field_name.entity.getTitle()

Mukeysh

srhcpa@debitsandcredits.com’s picture

Is there a way to directly reference a block with one of these methods? I am looking to reference the block in my page.html.twig file a such as this:
{{ nav#block-testsite-main-menu }}, but I can't find any useful documentation that supports this. I know that I can add a region and move the block to it, but I would like to do it programmatically, if possible.

vpa24’s picture

 <a href="{{ url('entity.node.canonical', {'node': node.field_name.target_id}) }}">
{{ node.field_name.entity.title.value }} </a>
snehamay’s picture

I have two content types: event and speaker.

For the event, I have created an entity reference field "speaker" and selected content type speaker as a reference.

Speaker content type has title, body and profile_picture fields.

To show the profile image url under event twig template, I used the following script: node.field_speaker[0].entity.field_profile_picture.entity.uri.value & node.field_speaker[1].entity.field_profile_picture.entity.uri.value

The strange thing is I am not getting the result for the second one on-words, but if I use to get speaker's name, it is working for all:  node.field_speaker[0].entity.title.value, node.field_speaker[1].entity.title.value and so on.

Any one faced that issue?

paper boy’s picture

All the solutions suggested above don't work for me on a Drupal 8.7 site. But actually it's quite straight forward how to display only a single field of a referenced node. 

Example:

I have a content type INVOICE with a field (field_customer) that references an entity of type CUSTOMER. The customer node has multiple fields, among them a company name and the customer's address. On my invoice I want to render the customer's address (field_address) from the related CUSTOMER entity. 

If I wanted to render the entire customer entity I'd simply set proper display options on the invoice node (ie. /admin/structure/types/manage/invoice/display) and output the customer field in the content render array inside the twig template of the INVOICE content type:

{{ content.field_customer }}

But if I wanted to only render one field of the customer entity, I'd use this in my INVOICE twig template:

{{ node.field_customer.entity.field_address|view }}

Note that we're using the node object instead of the content render array. Also make sure to append the |view filter at the end or you'll only see an error like "Exception: Object of type Drupal\address\Plugin\Field\FieldType\AddressFieldItemList cannot be printed.

dmegatool’s picture

That works ! Was looking exactly this kind of scenario. Thx ! 

I was looking at dpm(node) and didn't see my fields listed there. Even if I do node.field_reference_item, there's no "entity" array... How was I supposed to find/know that ? 

dpm(node) look like this : 

Node {#1399 ▼
  +in_preview: null
  #values: array:25 [▶]
  #fields: array:9 [▶]
  #fieldDefinitions: array:26 [▶]
  #languages: array:4 [▶]
  #langcodeKey: "langcode"
  #defaultLangcodeKey: "default_langcode"
  #activeLangcode: "x-default"
  #defaultLangcode: "fr"
  #translations: array:1 [▶]
  #translationInitialize: false
  #newRevision: false
  #isDefaultRevision: "1"
  #entityKeys: array:4 [▶]
  #translatableEntityKeys: array:8 [▶]
  #validated: false
  #validationRequired: false
  #loadedRevisionId: "310"
  #revisionTranslationAffectedKey: "revision_translation_affected"
  #enforceRevisionTranslationAffected: []
  #entityTypeId: "node"
  #enforceIsNew: null
  #typedData: EntityAdapter {#2053 ▶}
  #cacheContexts: []
  #cacheTags: []
  #cacheMaxAge: -1
  #_serviceIds: []
  #_entityStorages: []
  #isSyncing: false
}

dpm(node.field_reference_item) : 

EntityReferenceFieldItemList {#6412 ▼
  #list: array:1 [▶]
  #langcode: "fr"
  #definition: FieldConfig {#1512 ▶}
  #name: "field_reference_item"
  #parent: EntityAdapter {#6298 ▶}
  #stringTranslation: null
  #typedDataManager: TypedDataManager {#309 ▶}
}

Like how am I supposed to find node.field_reference_item ? Or .entity ? I just don't get it. Hard to learn twig and drupal8 at the same time :) 

paper boy’s picture

I have no idea where this is documented exactly. I'm sure it is somewhere, but obviously well hidden. Actually I need node.entity_reference_field.entity.some_field.value all the time. 

C. S. Comfort’s picture

Where did you come across the view filter? I don't see it referenced anywhere in the docs, and when I try applying it I encounter the Twig Syntax Error: "Unknown view filter". I'm on Drupal 8.7.7.

{{ node.field_whats_fresh_feature.entity.field_hero_img|view }}

Thanks!

dmegatool’s picture

That's from the Twig Tweak module iirc.

Hamza Chuhadhry’s picture

if i use twig tweak,everything works well, but i dont want to use twig tweak module, then without using of twig tweak how i can use view filter

emb03’s picture

I am getting the same error in 8.7.8

paper boy’s picture

As @dmegatool already said, install twig tweak module. It has some handy functions. see https://www.drupal.org/docs/8/modules/twig-tweak/cheat-sheet

emb03’s picture

I do have twig tweak installed: Version: 8.x-1.9 

paper boy’s picture

Are you trying to print an image field? Have a look at this answer at Stack Overflow.

It's odd you're seeing the view filter error message, when Twig Tweak is installed and enabled, but probably it's related to image fields.

iknowbryan’s picture

This works perfect! 

But I noticed that it's pulling from the DEFAULT view mode of the referenced entity.

Is it possible to reference a different one e.g. FULL or TEASER?

I tried:

{{ node.field_reference.entity.field_name|view|teaser }}

{{ node.field_reference.entity.field_name|teaser|view }}

{{ node.field_reference.entity.field_name|teaser }}

All threw errors.

Any ideas??

-=b=-

tostinni’s picture

To use a different display mode, according to the doc you can do 

{{ node.field_reference.entity.field_name|view('teaser')}}
DarkteK’s picture

And also if you don't want the render stuff for those fields, you can use:

{{ node.field_from_node.field_from_inner_entity[0].get('value').getValue() }}

And if you want to obtain the url link:

{{ node.field_from_node.field_from_inner_entity[0].get('uri').getValue() }}
CoolClick’s picture

Thank you for this explanation.  I will I found it hours ago.

rfletcher73’s picture

I am using Paragraphs module but I am thinking that the same strategy should apply to built-in fields as well. It requires two templates though and i think that might make it easier to understand.

I have a paragraph type that has some fields like title, body, and then a paragraph entity reference field that references a paragraph type that has an image and a link. 

In the first template paragrap--top-level-paragraph-content-type--default.html.twig, I can output values like {{content.field_title}}.

When i get to the entity reference field, i just output it like {{content.field_name}}

With twig debug enabled, i can see what template i need to edit change that referenced entity.

I create a second template called paragraph--image-links-items--default.html.twig and now i can change the html there in the same way i modified the first template.  I just try to imagine that the entity referece field type is just a connection to those other fields.

Hamza Chuhadhry’s picture

I can get all other values without using twig tweak module, but i cant get image value, please give me a solution how to use view filter without using twig tweak, and if i dont use twig tweak the only problem,i can't get image value,how i can get image value