0

I have a series of Views Exposed Forms across a Drupal 8 website. My goal is to generate unique template suggestions so I can theme each individual input and their labels differently as needed.

Here is my current approach. Placed into theme.theme. I've hit a brick wall.

function HOOK_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    $form['#attributes']['twig-suggestion'] = $form['#id'];
}

function HOOK_theme_suggestions_input_alter(&$suggestions, array $variables) {
    $element = $variables['element'];

    if (isset($element['#attributes']['twig-suggestion'])) {
      $suggestions[] = 'input__' . $element['#type'] . '__' . $element['#attributes']['twig-suggestion'];
    }
}

function HOOK_theme_suggestions_form_element_label_alter(&$suggestions, &$variables, $hook) {
    $element = $variables['element'];

    if (isset($element['#attributes']['twig-suggestion'])) {
      $suggestions[] = 'label__' . $element['#attributes']['twig-suggestion'];
    }
}

All input and label [#attributes] are null via Kint.
Here are the URLs I have referenced for background:

1) http://kevinquillen.com/drupal/2017/01/28/adding-twig-template-suggestions-for-form-elements

2) https://www.chapterthree.com/blog/how-to-create-custom-theme-suggestions-drupal-8

3) https://yellowpencil.com/blog/getting-granular-with-drupal-eight-forms/

0
  1. Should add #attributes to your element form so the form alter should be like:

function HOOK_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    $form['name_of_element']['#attributes']['twig-suggestion'] = $form['#id'];
}

  1. HOOK_theme_suggestions_input_alter will works only with input elements textfield.
  • You are so welcome, i'm glad that helped :) – berramou Jan 15 at 11:04

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.