Skip to content

Instantly share code, notes, and snippets.

@reinis-kinkeris
Last active May 26, 2017 08:56
Show Gist options
  • Save reinis-kinkeris/b8866581924798d780e9ff3217ea1eda to your computer and use it in GitHub Desktop.
Save reinis-kinkeris/b8866581924798d780e9ff3217ea1eda to your computer and use it in GitHub Desktop.
D8 - Implements form inner wrapper with suggestions so form elements can be rearranged.
<?php
/**
* Implements hook_form_alter().
*
* @param $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
* @param $form_id
*/
function MY_THEME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
// If #theme is set we test if it's a string. If it's a string we convert to
// array so we can append our base theme. If no #theme was specified by initial render
// array, FormBuilder adds $form_id and $form_base_id to #theme array.
if (isset($form['#theme'])) {
if (!is_array($form['#theme'])) {
$form['#theme'] = [
$form['#theme'],
];
}
}
$form['#theme'][] = 'form_inner';
}
/**
* Implements hook_theme_suggestions_alter().
*
* @param array $suggestions
* @param array $variables
* @param string $hook
*/
function MY_THEME_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
switch ($hook) {
case 'form_inner':
// Add suggestions for provided #theme hooks.
foreach (array_reverse($variables['form']['#theme']) as $theme) {
if ($theme !== $hook) {
$suggestions[] = $hook . '__' . $theme;
}
}
break;
}
}
/**
* Implements hook_preprocess_HOOK().
*
* @param $variables
*/
function MY_THEME_preprocess_form_inner(&$variables) {
// We unset #prefix and #suffix if they were provided because
// forms #theme_wrapper which invokes theme 'form' already has
// rendered #prefix and #suffix.
if (isset($variables['form']['#prefix'])) {
unset($variables['form']['#prefix']);
}
if (isset($variables['form']['#suffix'])) {
unset($variables['form']['#suffix']);
}
}
/**
* Implements hook_theme().
*/
function MY_THEME_theme() {
// Define default theme for form inner wrapper.
return [
'form_inner' => [
'render element' => 'form',
// If you like to keep your templates structured in folder, keep 'path'
// property, otherwise remove it.
'path' => drupal_get_path('theme', 'MY_THEME') . '/templates/form',
],
];
}
{#
/**
* @file
* Default theme implementation for a 'form_inner'.
*
* Available variables
* - form: Contains form elements.
*
* @see template_preprocess_form_inner()
*
* @ingroup themeable
*/
#}
{{ form }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment