0

Background:

I would like to alter the classes that are added to a rendered field in Drupal 9 in a custom module. I'm trying to use hook_preprocess_field and I'm not sure if this will work or if there is a better alternative.

based on: https://www.drupal.org/forum/support/module-development-and-code-questions/2017-03-31/add-class-to-field-in-drupal-8

I have the following:

function my_module_preprocess_field__field_pricing_grid_items(&$vars)
{
  
  foreach(array_keys($vars['items']) as $delta)
  {
    $vars['items'][$delta]['attributes']->setAttribute('class', 'my-class');
  }
}

This works for adding a class but I can't figure out how to add a class to the parent div. enter image description here

Result

 <div class ="field__items">
         <div class ="field__item CUSTOM-CLASS"></div>
      </div>

Desired result:

 <div class ="field__items CUSTOM-CLASS">
     <div class ="field__item></div>
  </div>

Questions:

  1. How can I add a class to the parent div? Is that possible with this hook?
  2. Would an alternative approach of maybe overriding the field with a template in my module work? The theme template would be field--field-pricing-grid-items.html.twig Is there a way to override the theme with a module?
  3. If neither of these approaches make sense what would be a possible way of achieving this.

1 Answer 1

0

I was going with the wrong approach.

What worked:

I needed to use hook_theme in my /my_module/my_module.module file

function MY_MODULE_theme($existing, $type, $theme, $path) {
  return [
    'field__field_pricing_grid_items' => [
      'base hook' => 'field',
      'path' => $path . '/templates/field',
    ],
  ];
}

then it was easy to override field.html.twig with /my_module/templates/field/field--field-pricing-grid-items.html.twig

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.