Description
I've implemented the cookbook solution for dynamic generation of submitted forms across several projects. Sometimes these forms need to add/update/remove several fields, so my JavaScript replaces the entire form - not just a single, hard-coded element like in the example. My controllers typically look something like this:
public function testAction(Request $request)
{
$entity = new Entity();
$form = $this->createForm('foo', $entity);
$form->handleRequest($request);
if ($form->isValid() && !$request->isXmlHttpRequest()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush($entity);
return $this->redirectToRoute('controller_index');
}
return ['form' => $form->createView()];
}
The problem
This works pretty well, but there's one major annoyance - AJAX submissions of incomplete forms result in lots of red errors everywhere. This occurs because Symfony validates the form by default during $form->handleRequest($request)
.
The cookbook recommends supressing form validation by stopping propagation of the POST_SUBMIT
event. However, I have other services listening for that event, so this approach isn't feasible.
I'm currently restoring to re-building the form just prior to the return
:
// ...
// Don't show any errors on partial AJAX submissions
if ($request->isXmlHttpRequest()) {
$form = $this->createForm('foo', $entity);
}
return ['form' => $form->createView()];
This works, but it seems kinda kludgy and not like an ideal solution, which is why I've tagged this [DX]
. It would be great if Symfony could provide a built-in method to prevent this common problem without weird workarounds.
Proposed solutions
Would it be possible to add a clearErrors()
method to FormInterface
? Ideally this would remove any previously-set validation errors (as if the form were never validated).
Alternatively, perhaps we could have some way of easily hiding/removing errors from the view? Maybe a boolean flag on the createView
method, a FormView::clearErrors
method, a setting on the FormRenderer
, or something to that effect?