Symfony2 : Two forms in a same page
This did the trick for me in Symfony 3 (should also work for Symfony 2):
$form1 = $this->createForm(
MyFirstFormType::class
);
$form2 = $this->createForm(
MySecondFormType::class
);
if ($request->isMethod('POST')) {
$form1->handleRequest($request);
$form2->handleRequest($request);
if ($form1->isSubmitted()) {
// Handle $form1
} else if ($form2->isSubmitted()) {
// Handle $form2
}
}
You have to treat the forms separately:
if('POST' === $request->getMethod()) {
if ($request->request->has('form1name')) {
// handle the first form
}
if ($request->request->has('form2name')) {
// handle the second form
}
}
This is perfectly explained in Symfony2 Multiple Forms: Different From Embedded Forms (temporarily unavailable - see below)
Update
As the link provided above is temporarily unavailable, you can see an archive of that resource here.
The problem is that you have two nameless forms (input names like inputname
instead of formname[inputname]
, and thus when you bind the request to your form and it gets validated it detects some extra fields (the other form) and so it is invalid.
The short-term solution is to create a named builder via the form factory, so instead of:
$form = $this->createFormBuilder(null)
you should use:
$form = $this->get("form.factory")->createNamedBuilder("my_form_name")
The long term solution would be to create your own form classes, that way you can keep your form code separate from the controller.