Score:0

Add class to field parent with a preprocess hook in a custom module?

cn flag

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.
Score:0
cn flag

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

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.