Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By kopeboy on
How to add the term id (tid) as a CSS class on every taxonomy term field?
Example: field_tags
Multiple value. If I display it using the Link formatter, I have this result:
<div class="field field-name-field-tags">
<a href="/tags/tag-1" typeof="skos:Concept" property="rdfs:label skos:prefLabel">Tag 1</a>
<a href="/tags/tag-2" typeof="skos:Concept" property="rdfs:label skos:prefLabel">Tag 2</a>
</div>
on which I would like to add the term id as a CSS class, like:
...
<a href="/tags/tag-1"
class="tid-1" typeof="skos:Concept" property="rdfs:label skos:prefLabel">Tag 1</a>
<a href="/tags/tag-2"
class="tid-2" typeof="skos:Concept" property="rdfs:label skos:prefLabel">Tag 2</a>
...
Comments
see template_preprocess_field
Himanshu
Thank you!
Thank you!
Should I put this in my theme's template.php ?
And is the tid already in ['#options']['entity'] or do I need to load anything more?
Yes, you can get the tid with
Yes, you can get the tid with: ['#options']['entity']->tid.
Yes, you can put it in your template.php file in a hook like this one:
8.4
Thanks,
Mahmoud Zayed
Another approach
In my case (Drupal v.8.4.5, Drupal commerce 2.4, custom field for product variation type) the row
$variables['items'][$index]['content']['#options']['attributes']['class'][] = 'my-class'
didn't work. I used:
with success.
Try Attribute::addClass
I found that this:
works for tags printed as links...it applies the class directly to the <a> tag. For other scenarios, such as plain text output, it may not work. And this:
Targets the wrapper around the entire field—not each individual item within the field, in case you want the classes on those to be different.
If you want to target the wrapper div around each item in a multi-value field, use:
See Attribute::addClass for more.
Term id
Any idea how to get the term id as a class instead of a custom class?
For Drupal 8
For Drupal 8
Error: Call to a member
How to get taxonomy id?
Works great! Thanks
Works great!
Thanks