Theme colour switcher

Get raw values from Entity Group Field in Twig

This is probably a pretty niche topic, but for anyone out there using the Group module and the very useful Entity Group Field module to add content to groups, it may be handy.

I previously posted about how to get the rendered value of this field in Twig, but what if you want/need to get individual raw values?

Today I had to do just that; I needed to check the type of each group referenced from the field and only display groups of a certain type. The invaluable Devel module came to the rescue.

In the "Load (with references)" sub-menu tab under the Devel menu tab on the content, you can find the entitygroupfield array with all its values. Here's an example of what I had to do:

{% if node.entitygroupfield.0 %}
      <div>
        <strong>{{ 'Client'|t }}</strong><br />
        {% for key, value in node.entitygroupfield %}
          {% if node.entitygroupfield[key].entity.group_type.target_id == 'client' %}
            {{ node.entitygroupfield[key].entity.label.value }}
          {% endif %}
        {% endfor %}
      </div>
    {% endif %}

We're checking first if the field has a value (if the content is in a group). Note that node.entitygroupfield.value is not valid.

Then, we loop over the field values (it's a multi-value field as the content can be added to unlimited groups) and check the group type for each one. If it's a Client group, we print the group name.

That's it. Pretty simple. There are a lot more values in there and you could get really complex with chained entities and displaying content from the groups and their entities and whatnot. This is just an example to get you started; again, Devel is your friend to figure out anything you may need to display.

Tags:

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.