May 17, 2018 Javier Eguiluz

Adding help messages to form fields is a common need in web applications. However, the Symfony Form component doesn't provide this feature and you need to create a Form extension like the following:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 namespace App\Form\Extension ; use Symfony\Component\Form\AbstractTypeExtension ; use Symfony\Component\Form\Extension\Core\Type\FormType ; use Symfony\Component\Form\FormInterface ; use Symfony\Component\Form\FormView ; use Symfony\Component\OptionsResolver\OptionsResolver ; class HelpMessageExtension extends AbstractTypeExtension { public function getExtendedType () { return FormType :: class ; } public function buildView ( FormView $view , FormInterface $form , array $options ) { $view -> vars [ 'help' ] = $options [ 'help' ] ?? '' ; } public function configureOptions ( OptionsResolver $resolver ) { $resolver -> setDefaults ([ 'help' => null ]); } }

And then create your own form theme to display this help message:

1 2 3 4 5 6 7 8 9 {% use "bootstrap_4_layout.html.twig" %} {% block form_row %} {# ... #} {% if form.vars.help ?? false %} <div class="form--help"> {{ form.vars.help }} </div> {% endif %} {% endblock form_row %}

In Symfony 4.1, all this will no longer be necessary because you can define the help message of any form field using the help option:

1 2 3 4 // ... $builder -> add ( 'email' , null , [ 'help' => 'Make sure to add a valid email' , ]);

This is how the help message looks when using our Bootstrap 4 form theme:

Thanks to the diversity initiative we prioritize web accessibility in everything we do, so the form theme has been updated to include the required aria-describedby attribute in the form fields that include a help message.