I\'ve got two forms in a same page.
My problem is when I tried to submit a form, it\'s like it tried to submit the second form below in the page as well.
As
Using Named forms is a viable solution for handling multiple forms, but it can get a little messy, particularly if you're generating forms dynamically.
Another method, as of Symfony 2.3, is to check which submit button was clicked.
For example, assuming that each form has a submit button named 'save':
if ('POST' == $Request->getMethod())
{
$form1->handleRequest($Request);
$form2->handleRequest($Request);
$form3->handleRequest($Request);
if ($form1->get('save')->isClicked() and $form1->isValid())
{
//Do stuff with form1
}
if ($form2->get('save')->isClicked() and $form2->isValid())
{
//Do stuff with form2
}
if ($form3->get('save')->isClicked() and $form3->isValid())
{
//Do stuff with form3
}
}
I believe this has a small amount of additional overhead as compared to the named builder method (due to multiple handleRequest calls), but, in certain cases, it results in cleaner code. Always good to have multiple solutions to choose from. Some of the additional overhead could be alleviated via nested if/else statements, if necessary, but, unless we're talking about dozens of forms per page, the additional overhead is negligible in any case.
Here's an alternate implementation using anonymous functions that minimizes code repetition:
$form1Action = function ($form) use (&$aVar) {
//Do stuff with form1
};
$form2Action = function ($form) use (&$anotherVar) {
//Do stuff with form2
};
$form3Action = function ($form) use (&$yetAnotherVar) {
//Do stuff with form3
};
$forms = [$form1 => $form1Action,
$form2 => $form2Action,
$form3 => $form3Action];
if ('POST' == $Request->getMethod())
{
foreach ($forms as $form => $action)
{
$form->handleRequest($Request);
if ($form->get('save')->isClicked() and $form->isValid())
{
$action($form);
}
}
}