public static function Dazzler::preRenderForm in Formdazzle! 2.x
Adds template suggestions to forms.
Instead of using hook_form_alter or hook_theme_suggestions_alter, we delay adding suggestions until the form's pre_render phase.
Parameters
array $form: A render array of the form.
Return value
array The modified form.
3 calls to Dazzler::preRenderForm()
- DazzlerTest::testPreRenderForm in tests/
src/ Unit/ DazzlerTest.php - @covers ::preRenderForm
- DazzlerTest::testPreRenderFormNoDebugging in tests/
src/ Unit/ DazzlerTest.php - @covers ::preRenderForm
- DazzlerTest::testRepeatedPreRenderFormCalls in tests/
src/ Unit/ DazzlerTest.php - @covers ::preRenderForm
File
- src/
Dazzler.php, line 71
Class
- Dazzler
- A class providing methods to modify Drupal form elements.
Namespace
Drupal\formdazzleCode
public static function preRenderForm(array $form) {
// We always set these properties in formAlter(). If this is missing, an
// earlier call to preRenderForm() has already consumed the #formdazzle
// data. So we don't need to run this function.
if (isset($form['#formdazzle']['form_id'])) {
$form_id = $form['#formdazzle']['form_id'];
$form_id_suggestion = self::getFormIdSuggestion($form, $form_id);
self::traverse($form, $form_id, $form_id_suggestion);
// We unset the #formdazzle data to prevent repeated preRenderForm() calls
// from altering the form again.
unset($form['#formdazzle']);
// When #theme is set, Drupal ignores #markup, UNLESS none of the #theme
// suggestions are implemented. Which means we can safely set #markup to
// print out Twig debugging comments about the not-implemented #theme
// suggestions.
/** @var \Twig\Environment $twig_service */
$twig_service = \Drupal::service('twig');
if ($twig_service
->isDebug() && isset($form['#theme'])) {
// Expand the list of theme suggestions.
$suggestions = $form['#theme'];
if (is_string($suggestions)) {
$suggestions = [
$suggestions,
];
}
$hook = $suggestions[array_key_last($suggestions)];
while ($pos = strrpos($hook, '__')) {
$hook = substr($hook, 0, $pos);
$suggestions[] = $hook;
}
// Add an HTML comment that mimics the Twig debugging comments added by
// twig.engine. @see twig_render_template()
foreach ($suggestions as &$suggestion) {
$suggestion = Html::escape(strtr($suggestion, '_', '-') . '.html.twig');
}
$form['#markup'] = Markup::create("\n\n<!-- THEME DEBUG -->" . "\n<!-- THEME HOOK: No templates found. -->" . "\n<!-- FILE NAME SUGGESTIONS:\n * " . implode("\n * ", $suggestions) . "\n-->");
}
}
// #pre_render functions return the elements they are pre-rendering.
return $form;
}