Symfony News

New in Symfony 4.2: Clear form errors

Colin O'Dell

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
$task = ...;
$form = $this->createForm(TaskType::class, $task);
// ...

$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
    // ...

    $form->clearErrors();

    // this removes errors from the form and all its children forms
    $form->clearErrors(true);

    // ...
}

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


Be trained by Symfony experts - 2018-11-12 Clichy - 2018-11-12 Clichy - 2018-11-14 Clichy


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook