⌛ This article is now 3 years and 7 months old, a quite long time during which techniques and tools might have evolved. Please contact us to get a fresh insight of our expertise!
Display Symfony form errors, without any submit
Imagine our database contains some invalid entries and we build a form allowing us to complete the entity: how can our users know which fields are invalid and need completion?!
Building a Form with that invalid entity and displaying it to the user is not enough, no errors are going to be displayed until the user submit the form.
In Symfony, form validation is done when the form is submitted thanks to the ValidationListener
POST_SUBMIT handler.
Upon submit, an action is basically splitted in two paths:
- either the form is valid (
$form->isValid()
) and we redirect; - either it’s not and the form is displayed again, with nice errors alongside the submitted data.
What if we want this second path, with all the invalid states of our data, as soon as the form is displayed the first time?
Here is how I did it, hope it helps!
Section intitulée submit-the-form-artificiallySubmit the form artificially
We are going to change the typical action logic a bit, to introduce a new code path when the form is not submitted:
$form = $this->createForm(EmployeeType::class, $employee);
$form->handleRequest($request);
- if ($form->isSubmitted() && $form->isValid()) {
- // Save the object
- return $this->redirectToRoute('home');
+ if ($form->isSubmitted()) {
+ if ($form->isValid()) {
+ // Save the object
+ return $this->redirectToRoute('home');
+ }
+ } else {
+ $form->submit(null, false);
}
The important call is $form->submit(null, false);
. It will trick the form to run all the “submit” events, including the ValidationListener
POST_SUBMIT
. So all our initial data (the $employee
object here) are run against validation and our user knows what’s missing.
But I would not write an article just to show this. There is a catch: the CSRF protection is also triggered and will return an error, because the token is not part of the initial data (and that’s the same for all the fields added dynamically).
One way of dealing with it without disabling this important security feature is to get a valid token from the token manager attached to the form. This is kind of hacky but as we do it only when the form is not submitted, there is no issue:
$csrfManager = $form->getConfig()->getOption('csrf_token_manager');
$csrfId = $form->getConfig()->getOption('csrf_token_id');
$csrfField = $form->getConfig()->getOption('csrf_field_name');
$tokenId = $csrfId ?: ($form->getName() ?: \get_class($form->getConfig()->getType()->getInnerType()));
$form->submit([$csrfField => (string) $csrfManager->getToken($tokenId)], false);
(We use the same logic as FormTypeCsrfExtension
.)
With this version, our initial page load displays the complete form with nice errors on fields that need to be completed and no unsolicited CSRF error.
Section intitulée final-action-codeFinal action code
The complete action code is:
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
// Save the object
return $this->redirectToRoute('home');
}
} else {
// Build the CSRF like FormTypeCsrfExtension to fake form submit (used to display initial errors)
$csrfManager = $form->getConfig()->getOption('csrf_token_manager');
$csrfId = $form->getConfig()->getOption('csrf_token_id');
$csrfField = $form->getConfig()->getOption('csrf_field_name');
$tokenId = $csrfId ?: ($form->getName() ?: \get_class($form->getConfig()->getType()->getInnerType()));
$form->submit([$csrfField => (string) $csrfManager->getToken($tokenId)], false);
}
At the moment, I don’t see any other place this could be done (FormExtension
or FormEvent
), so if needed on multiple forms and actions, a refactoring must be done.
This feature / need has not gained much attention on Github when it was suggested so I guess this is not a common need – anyway I hope it solves something for you!
Commentaires et discussions
Nos formations sur ce sujet
Notre expertise est aussi disponible sous forme de formations professionnelles !

Symfony avancée
Découvrez les fonctionnalités et concepts avancés de Symfony
Ces clients ont profité de notre expertise
Dans le cadre d’une refonte complète de son architecture Web, Expertissim a sollicité l’expertise de JoliCode afin de tenir les délais et le niveau de qualité attendus. Le domaine métier d’Expertissim n’est pas trivial : les spécificités du marché de l’art apportent une logique métier bien particulière et un processus complexe. La plateforme propose…
Nous avons construit un extranet afin de de simplifier les tâches quotidiennes de gestion, que ce soit pour les utilisateurs (départements, associations, mandataires, accueillants et accueillis) et l’équipe de Cettefamille. Le socle technique utilisé est Symfony, PostgreSQL, Webpack, VanillaJS. L’emploi de ces technologies modernes permet aujourd’hui…
JoliCode accompagne l’équipe technique Dayuse dans l’optimisation des performances de sa plateforme. Nous sommes intervenus sur différents sujets : La fonctionnalité de recherche d’hôtels, en remplaçant MongoDB et Algolia par Redis et Elasticsearch. La mise en place d’un workflow de réservation, la migration d’un site en Twig vers une SPA à base de…