New in Symfony 4.1: Form field help
May 17, 2018 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Sadly my project can't wait for 4.1, but the example given in this post was exactly what I needed!
Maybe a note could be added on the news or the doc?