0

I have an exposed field with a "checkboxes" field, that I need to theme by adding (and removing) Drupal's default classes. I found close to nothing about how to do that, excepted this answer.

So, I did the following thing:

function MY_THEME_preprocess_form_element(array $variables) {
  $elements = $variables['element'];
  if ($elements['#type'] == 'checkbox' && strpos($elements['#attributes']['id'], 'field-news-tag')) {
    $variables['element']['#attributes']['class'][] = 'c-tag-filters__item__input';
  }
}

I had to use strpos() because the checkboxes are related to a taxonomy term, so the id is different, with the taxonomy term id added at the end. My code, as is, doesn't return any error but no class is added to the checkbox.

Am I on the right track? Or is this doable only from the hook_form_alter() ?

Thank you in advance.

4
  • Look in the function sig - array $variables - you're throwing away changes to $variables. Make sure you're taking it by reference instead (array &$variables)
    – Clive
    Jul 10, 2020 at 15:07
  • I changed $variables for &$variables, sadly didn't work
    – Jaeger
    Jul 10, 2020 at 15:09
  • just an idea - you can achieve the result within twig templates - there you can get all the classes which will be rendered and add/remove any you want. Reference drupal.org/project/drupal/issues/2347511
    – Ales
    Jul 10, 2020 at 15:17
  • I've overriden a form-element.html.twig template where I can do whatever I want with the label, but the input itself is just a Markup string. Is there a way to do so in the form-element, or should I override something else?
    – Jaeger
    Jul 10, 2020 at 15:19

0

Your Answer

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

Browse other questions tagged or ask your own question.