New in Symfony 4.1: Form field help

News - NETCreator - 2018-05-17 10:15:16

Contributed by
Mathieu Piot
in #26332.

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.


Be trained by Symfony experts - 2018-05-22 Clichy - 2018-05-22 Paris - 2018-05-22 Clichy

Source: Symfony
Latest Posts
NETCreator CMS

Search
Free Hosting