Search code examples
entitydrupal-8preprocessorvocabularytwig-filter

D8 How do I retrieve the value of a custom field on a vocab term for the field--entity-reference.html.twig file?


My goal is to colour code vocabulary terms based on a field_topic_colour which I've added to the vocabulary. There are other vocabularies which do not have this field. So, I need to check and see if it exists for a certain term and then fetch the value so I can create my classes and get the buttons to have the correct color.

With kint I can see the value, but I cannot figure out how to drill down to it in twig or via preprocessing. All the Qs i've found deal with vocab terms in nodes, not in the terms themselves.

Here is my kint screen shot: enter image description here

I'm trying to get to "primary" (which is the keyword to tell my Bootstrap subtheme what color to use) under the field_topic_colour.

What exactly must I write in the preprocessing function?

function MYTHEME_preprocess_field__entity_reference($variable) {
  //I need code to return a string like this (I think) where "primary"
  //is the value from my custom field in the term.
  $color = ????? (primary)
  $mytag = 'class="btn- . $color . ">TERM-NAME...TERM_URL...
}

I can clean the php on my own, didn't worry about it in the above example. I just need to get the value for my field...

I've checked the cheatsheets here: https://wizzlern.nl/sites/wizzlern.nl/files/artikel/drupal-content-entity-8.0.pdf but it seems i really need some specific examples and EXPLANATIONS of why something works, so I can hopefully start to logically figure it out next time.


Solution

  • Adding the answer now. My final code in the field--entity-reference.html.twig file:

    {% for item in items %}
      {% set mylabel %}
        {{ item.content }}
      {% endset %}
      {% set myclass %}
        {{ item.content['#options'].entity.vid.0.value['target_id'] }}
      {% endset %}
      {% set myclass = myclass|replace({'_':'-'}) %}
        <div{{ item.attributes.addClass('taxonomy--item') }}>
          <a class="btn-small btn-primary tag-{{ myclass|trim }}" href="{{ item.content['#url'] }}" role="button">{{ mylabel|striptags }}</a>
        </div>
    {% endfor %}
    

    HERE is the code needed in a node to access the parent vocabulary of the taxonomy terms in the node. (That is, individual tags on a content type node).

    item.content['#options'].entity.vid.0.value['target_id']
    

    NOTE: This is on Drupal 8.5.3 and none of my "tags" have more than one parent.