Skip to content

Instantly share code, notes, and snippets.

@mattschaff
Created December 12, 2019 22:55
Show Gist options
  • Save mattschaff/0ce197bf83eec755b2eedcdef2416ce1 to your computer and use it in GitHub Desktop.
Save mattschaff/0ce197bf83eec755b2eedcdef2416ce1 to your computer and use it in GitHub Desktop.
Drupal 8: Add unique ID to theme suggestions for form elements
<?php
/**
* @file
*/
/**
* Implements hook_form_alter()
*/
// Add unique form ID to theme suggestions for form elements.
function example_form_alter(&$form, $form_state, $form_id) {
$form_type = 'test-type';
foreach (Element::children($form) as $key) {
$form[$key]['#form_type'] = $form_type;
}
$form['#form_type'] = $form_type;
$form['actions']['submit']['#form_type'] = $form_type;
// Modifications to clear/reset button
if (!empty($form['actions']['reset'])) {
$form['actions']['reset']['#form_type'] = $form_type;
}
}
/**
* Implements hook_theme_suggestions_alter()
*/
function example_theme_suggestions_alter(&$suggestions, $variables, $hook) {
// Add unique form ID to theme suggestions for form elements.
$form_hooks = [
'container',
'form',
'select',
'input',
'checkboxes',
'checkbox',
'form_element',
'form_element_label',
'input__checkbox',
'bef_checkboxes',
'fieldset',
];
if (in_array($hook, $form_hooks)) {
_add_unique_form_id_to_suggestions($suggestions, $variables, $hook);
}
}
/**
* Helper function that adds a unique form ID to the form element theme suggestions
*/
function _add_unique_form_id_to_suggestions(&$suggestions, $variables, $type) {
$element = $variables['element'];
if (isset($element['#form_type'])) {
$suggestion_suffix = str_replace(['-'], '_', ($type === 'form' ? '' : $element['#id'] . '__' ) . $element['#form_type']);
$suggestions[] = $type . '__' . $suggestion_suffix;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment