user1018146
user1018146

Reputation:

Symfony2 - Multiple forms in one action

I implemented a page to create an instance of an entity and a user related to this. My problem is to bind the request after the submit.

Now i have this :

$formA = $this->createForm(new \MyApp\ABundle\Form\AddObjectForm());
$formB = $this->createForm(new \MyApp\UserBundle\Form\AddUserForm());

if ($request->getMethod() == 'POST')
{
    $formA->bindRequest($request);
    $formB->bindRequest($request);

    if ($formA->isValid() && $formB->isValid())
    {
    }
    // ...
}

With formA and formB extends AbstractType. But, naturally, $formA->isValid() returns false. How can I do to "cut" the request for example ?

Upvotes: 4

Views: 11344

Answers (2)

fray88
fray88

Reputation: 820

I know that has been a long time since the answer, but maybe if someone is looking for it this could be helpfull.

I've got two forms: user_form and company_form, and the submit has take place in the same function of the controller. I can know wich form has been submit with the follow code:

    if ($request->getMethod() == 'POST') {

       $data = $request->request->all();

        if (isset($data['user_form'])) //This if means that the user_form has been submit.
        { 

The company_form will pass through the else.

Upvotes: 5

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44831

If your forms are related and need to be processed and validated at once, consider using embedded forms. Otherwise, use a separate action for each form.

If you need to provide a select field to choose a user from existing ones, consider using an entity type field.

Upvotes: 6

Related Questions