I generate a simple module "myformtest" with a simple Class form "MyformtestForm". I want override the default form template and pass to the template a custom array generated from my build method of form Class.
I followed this great tutorial . I added a "_theme_suggestions_alter" hook in my "myformtest.module", I also added the hook theme.
My "suggestion theme" is "form--myformtest-form.html.twig". Then in my module directory:
- I added a sub-directory "templates"
- I added the twig file "form--myformtest-form.html.twig" in the sub-directory "drupal/modules/custom/myformtest/templates"
In my .twig file, I added this simple code. (I copied it from the drupal/core/themes/classy/templates/form/form.html.twig and added the h1 html element for override)
<h1>TEST</h1>
<form{{ attributes }}>
{{ children }}
</form>
I clear caches (drush cr) and I reloaded my form page. The html element h1 "test" is displayed but not the form :/ I thinked my .twig file override the form.html.twig default theme...
Did I miss something ? Why the form isn't displayed, how can I fix it ? And how can I pass a custom array from my build method of form Class to my twig template ?
Below, the code of my .module file :
/**
* Implements hook_theme_suggestions_alter().
*/
function myformtest_theme_suggestions_alter(array &$suggestions, array $variables, $hook)
{
if (isset($variables['element']) && isset($variables['element']['#type']) && $variables['element']['#type'] == 'form') {
$original_theme_hook = $variables['theme_hook_original'];
array_unshift($suggestions, $original_theme_hook . '__' . str_replace('-', '_', $variables['element']['#id']));
}
}
/**
* Implements hook_theme().
*/
function myformtest_theme($existing, $type, $theme, $path)
{
// if I comment this function, the form is displayed (but without the html element h1 "test")
return array(
'form__myformtest_form' => array(
'render element' => 'form',
'template' => 'form--myformtest-form',
),
);
}
If I comment the myformtest_theme function, the form is displayed (but without the html element h1 "test") :
Thanks for help :)
Comments
Try element
Instead of {{ form }} , try {{ element }}