Score:1

How do I add a template suggestion for form input fields that have containers?

in flag

I've been able to successfully add the parent form ID to all form elements, based on these two questions: How can we find the id of the parent form in preprocess_HOOK() or HOOK_alter() theme functions? and Add the Form name to the theme suggestions input field.

However, the two elements I really need template suggestions for are inputs that have containers... therefore the parent form ID is added to the containers, not the inputs, and when I add the template suggestions the variable is blank (obviously).

I see there are modules like Formdazzle! which makes this easy, but I feel like I'm close - however I'm struggling to 'reach' the children (the inputs) of the form elements (the containers).

This is my current code:

 * Implements hook_form_alter().
 */
function HOOK_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  foreach (\Drupal\Core\Render\Element::children($form) as $key) {
    if ($form[$key]['#parents']) {
      $form[$key]['#attributes']['data-parent-form'] = $form['#id'];
    } else {
      // help!
    }
  }
}

/**
 * Implements hook_theme_suggestions_input_alter().
 */
function HOOK_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  $suggestions[] = 'input__' . $element['#type'] . '__' . $element['#attributes']['data-parent-form'];
}
leymannx avatar
ne flag
You could preprocess the containers check for your input in there, and if you find them, assign a variable to the input from in there. This variable can then be accessed in the suggestion hook variables later.
in flag
@leymannx I looked into this and ended up going with Formdazzle - I was trying to reinvent the wheel and in the end needed to save time (and worried another situation won't be covered in the future). This is definitely the way to proceed however.
leymannx avatar
ne flag
Yeah, [Formdazzle](https://www.drupal.org/project/formdazzle) always nice for form theming. Maybe add that as an answer below!
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.