2

I have an exposed form in a D8 view which includes several fields, output through form-element.html.twig (amongst others). I added a function:

function MYTHEME_preprocess_form_element(&$variables) {
...
}

This contains an 'element' key and I could add a class in there, BUT I see no way of identifying which form this is part of. The 'element' has a child '#parents' but this is simply the name of the field.

The whole point of this is to add some Bootstrap responsive classes to these different form items for layout. I tried template_preprocess_form and while I see the fields listed as elements, I don't see a way to add classes to the form element label.

What is best practice for theming D8 exposed forms?

Update: I used XDebug with PhpStorm to debug both MYTHEME_preprocess_form_element and MYTHEME_preprocess_form and explored the entire tree of $variables but could see nothing hinting at parent form ID or similar.

  • You are on the right track, if you use kint($variables);, you should be able to see what is in the array. I have done this to alter form elements, change the label order, add classes and such. For the exposed form, there might be a different theme hook which should show up in twig debug. – Danny Englander Aug 11 '16 at 16:17
  • @Danny Englander, do you have an example how to find the parent form of a form element? – 4k4 Aug 11 '16 at 16:24
  • @4k4, Not offhand for that specific thing, just throwing around some ideas here. – Danny Englander Aug 11 '16 at 16:35
  • 1
    Was at the same point as Nic some time ago, gave up on theming and used form build/alter for the bootstrap classes. – 4k4 Aug 11 '16 at 16:39
1

As @4k4 said, if all you want is to add some classes, then use hook_form_alter() or hook_form_FORM_ID_alter(). $form['your_element']['#attributes']['class'][] = 'your-class is all you need.

I'm pretty sure that single form elements don't have the form ID stored somewhere.

  • Thanks, but I really want to be able to change the label HTML node also (with some CSS classes) but doesn't seem available in $form in hook_form_alter – Nic Aug 12 '16 at 9:10
  • 2
    Then combine it. Add a class to the form element through form alter, then based on having that class (or any other thing, really), add that or another class to the $variables['label'] – Berdir Aug 14 '16 at 21:16
0

In order to set a class to the label, you can write your own form-element-label.html.twig.

  • Yeah, was thinking about that. But I want it only to affect this exposed filter on this view. – Nic Aug 12 '16 at 12:37

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.