4

I'm trying to look for a way to modify the markup for a form element without touching the default theme/template. Upon checking the source code, Drupal does not seem to recommend any theme suggestions for editing form elements. I have multiple views using the same field on the exposed filter. If I try to edit the form-element-label.html.twig it will affect all of the elements with the same field.

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form_element_label' -->
<!-- BEGIN OUTPUT from 'themes/iom/templates/layout/form-element-label.html.twig' -->
<label for="edit-field-themes-target-id" class="label">Themes</label>
<!-- END OUTPUT from 'themes/iom/templates/layout/form-element-label.html.twig' -->
1

1 Answer 1

2

Seems you have to implement two hooks. One to add the suggestion, and one to define a template. hook_theme_suggestions_HOOK_alter and template_preprocess_form_element (aka hook_preprocess_HOOK).

/**
 * Implementation of hook_theme_suggestions_form_element_alter().
 */
function MYTHEME_theme_suggestions_form_element_alter(array &$suggestions, array $variables) {
  if (\Drupal::service('path.current')->getPath() == '/user/login') {
    $suggestions[] = $variables['theme_hook_original'] . '--user-login';
  }
}

/**
 * Implementation of hook_preprocess_form_element().
 */
function MYTHEME_preprocess_form_element(&$variables, $hook, &$info) {
  $info['template'] = 'form-element--user-login';
}

Source: Form element template suggestion has no effect.

2
  • Hello, apologies for my ignorance. Lets say I have a view with an exposed filter. Is it possible to only target the form elements of a specific view? I'm trying to understand the answer you have suggested. Still new with drupal hooks. Let's say I want to create a theme suggestion for a form-element that has a label and select element
    – clestcruz
    Commented Sep 5, 2018 at 14:07
  • @clestcruz – You have to wrap the code inside the hooks with some if conditions to fire only according your logic. Check what's inside $variables, maybe there's something you can identify your view with. As last resort you can also check the current URL.
    – leymannx
    Commented Sep 5, 2018 at 14:33

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.