0

I have an entity reference field with multiple values, referencing various content using a custom view mode.

I need to apply the same custom class to each (delta) row.

By default Drupal (twig?) is applying a class of .field__items to each row, but this is not specific enough, as this is also used for other fields within the view mode.

What is the best way to achieve this?

  • Curious to know why Clive edited this post. I thought my follow up might useful for others. – MrPaulDriver Jun 23 '17 at 16:01
2

You can add classes in the twig template directly, or through a preprocess function.

Preprocess

Docs provide some patterns to follow: https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_field/8.2.x

function HOOK_preprocess_field(&$variables) {
  $element = $variables['element'];

  switch ($element['#field_name']) {
    case 'MY_FIELD_NAME':    
      $delta = 0;
      while(!empty($element[$delta])) {
        $variables['items'][$delta]['attributes']->setAttribute('class', 'custom-class-name');
        $delta++;
      }

      break;
  }
}

This applied the class to the entire entity, alongside field__item.

Template

If you have twig debugging enabled, you can see quickly what's a good template name. I tested with field--node--FIELD-NAME.html.twig. Using the field template from classy for example, just add the class at the end of the list.

{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    'custom-class-name',
  ]
%}

This applied the class just to the field, not the label. But you could modify the template to print the classes elsewhere.

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.