New in Symfony 4.2: Clear form errors

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

Contributed by
Colin O'Dell
in #27580.

Form events allow to dynamically modify Symfony Forms. They are used to show/hide fields depending on the value of other fields, to update the values of some field based on the value selected in another field, etc.

When using events, it's common to render the entire form and extract some parts of it using JavaScript. It's also common to do partial form submissions with AJAX. In all those cases it's useful to validate the form without actually showing the validation errors to the user.

That's why in Symfony 4.2 we've added a new clearErrors() method to remove any existing errors in the forms:

$task = ...;
$form = $this->createForm(TaskType::class, $task);
// ...


// this removes errors from the form and all its children forms

Because clearing the errors makes the form valid, clearErrors() should only be called after testing whether the form is valid.

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.


Nice feature, but the example seems a bit illogical. Correct me if I am mistaking but the "clearErrors"-Method only gets called if "$form->isValid()" returns true and therefore wouldn't do anything.
Thanks for this!

There is something I don't understand in the example above. I must be missing something. How can it be useful to call $form->clearErrors(); within a condition that checked $form->isValid()? From my knowledge, form errors are always empty in this context.
@Justus @Benoit you are right. I've just updated the example. Thank you!
Thank you for this feature.

Could you please guys give an idea why the boolean parameter is used to control the method's behavior?

Is it "a symfony" way? Couldn't find anything in the related PR. From my point of view, it would be better to have 2 functions.

Thank you in advance!

My guess is the boolean mirrors the getErrors() method.

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.