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.
Lastly, if you customize Symfony forms with Twig functions like
form_row()
, form_label()
, etc. you can now use a new function called
form_help()
to get the contents of the help message.
Thank you for that!!
Great job, Thank you !
Awesome
Great! Awesome! I needed this kind of feature for my apps, I'm really glad a simple "composer update" will give me access to it at the end of the month :D
This is good news !
Amazing coincidence; I was literally looking up how to best do this the other day.
Sadly my project can't wait for 4.1, but the example given in this post was exactly what I needed!
That is quite cool. Thanks.
disapeared after 1.4, returns in 4.1, hi again!
Thank you!
Awesome, thx !
Don't also forget to upgrade
symfony/twig-bridge
to v4.1+ if you want the help option effective with the bootstrap official theme!Maybe a note could be added on the news or the doc?