0

I have a Site with a Twig Template. I have an multiple entity references which I want to loop trough and print out the name, description of each entity.

In my template I'm using the following code to loop through entities.

{% for item in node.field_workers %}
 {{ item.entity.field_name.value }}
{% endfor %}

This loops trough all my entities but won't output any value whatsoever. I tried using kint() to debug the process. When I try kint(item.entity) it shows me the following structure:

protected fields --> field_name

When I try kint(item.entity.fields) it redirects me to 'drupal/install' page when I try to load the page.

What am I doing wrong?

2
  • 1
    IMO it’s easier to let the field render as normal, and tell the field display to use a view mode for this purpose. In the view mode you can set which fields to show and then theme it with a twig file.
    – Kevin
    Nov 29 '18 at 16:33
  • Try using the standard twig dump with the '|keys' filter to see the basic structure. E.g. dump( item.entity.field_name |keys). kint and dump tend to fill up memory and give bad results. You may find the value is an array and you need to add a [0] after the .value part. Drupal generally returns an array to allow for multivalue fields. The keys filter should help you find out.
    – CG Monroe
    Nov 29 '18 at 23:01
1

As Kevin says in his comment, Drupal will do most of the work for you if you use view modes on the referenced content type:

/admin/structure/types/manage/{referenced-content-type}/display

In your case, you might want to modify the Teaser view mode so that it hides all fields except for Name and Description. (If you are already using the Teaser for something else, you can create a new view mode.)

Then, when you render the entity reference field, just use the format "Rendered Entity" and configure the view mode that you wish to render (e.g., Teaser).

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.