Accessing fields of an entity reference in a view (views-view-fields.html.twig)

Viewed 1697

So i have 2 content types

  • Webinar
  • Person

Webinar has an entity reference field (label:speaker, id:field_person_speaker)

  • Person (multiple values)

I have a view (unformatted list of fields of content type webinar) on path /webinar with these fields

  • title
  • youtubeID
  • date
  • speaker (formatter: rendered entity)

I have a template (views-view-fields--vcon-webinar.html.twig) that renders a row:

{% set title = fields.title.content %}
{% set date = fields.field_webinar_date.content %}
{% set url = path('entity.node.canonical', { 'node' : row.nid}) %}
{% set speakers = fields.field_person_speaker.content %}

<div class="card h-100 shadow dl-webinar">
  <div class="card-body">
    <a class="dl-webinar-link" href="{{url}}"><span class="btn btn-light btn-sm dl-webinar-signup">Sign up</span></a>
    <div>
      <div class="d-flex">
        {{speakers}}
      </div>
    </div>
    <div>
      <div class="d-flex">
        <div class="p-3">
          <h4>{{title}}</h4>
          <p class="font-weight-light mb-0">{{date}}</p>
        </div>
      </div>
    </div>

  </div>
</div>

The issues is that i can't get the individual field values of the referenced entities (speaker). I need those field values (like: field_person_first_name) because i need full control of the output template.

<div class="dl-webinar-bio d-flex align-items-end flex-row-reverse  flex-fill">
    <div><p class="dl-webinar-bio-name"><strong>First name, Last name</strong> <small class="font-weight-light">Project manager</small></p></div>
</div>

Can please someone help me with this... thx....

1 Answers

The easiest way to get this is to render Person content type on a specific view mode. Then you override the template node--person-yourviewmode.html.twig with the exact HTML structure that you expect.

So you didnt change views-view-fields--vcon-webinar.html.twig template.

and in node--person-yourviewmode.html.twig :

<div class="dl-webinar-bio d-flex align-items-end flex-row-reverse  flex-fill">
    <div><p class="dl-webinar-bio-name"><strong>{{content.field_firstname}} {{ content.field_lastname}}</strong> <small class="font-weight-light">Project manager</small></p></div>
</div>

The above template will be called in views-view-fields--vcon-webinar.html.twig

Related