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.
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:
- How can I add a class to the parent div? Is that possible with this hook?
- 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?
- If neither of these approaches make sense what would be a possible way of achieving this.