Quantcast
Channel: Symfony Blog
Viewing all articles
Browse latest Browse all 3057

New in Symfony 4.1: Form field help

$
0
0
Mathieu Piot

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
namespaceApp\Form\Extension;useSymfony\Component\Form\AbstractTypeExtension;useSymfony\Component\Form\Extension\Core\Type\FormType;useSymfony\Component\Form\FormInterface;useSymfony\Component\Form\FormView;useSymfony\Component\OptionsResolver\OptionsResolver;classHelpMessageExtensionextendsAbstractTypeExtension{publicfunctiongetExtendedType(){returnFormType::class;}publicfunctionbuildView(FormView$view,FormInterface$form,array$options){$view->vars['help']=$options['help']??'';}publicfunctionconfigureOptions(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"%}{%blockform_row%}{# ... #}{%ifform.vars.help??false%}<div class="form--help">{{form.vars.help}}</div>{%endif%}{%endblockform_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 requiredaria-describedby attribute in the form fields that include a help message.

Lastly, if you customize Symfony forms with Twig functions likeform_row(), form_label(), etc. you can now use a new function calledform_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

Viewing all articles
Browse latest Browse all 3057

Trending Articles