3

How to create Named form builder to use few forms in one request Symfony 3

$registration_form = $this->createFormBuilder()
                ->setMethod('POST')
                ->add('username', TextType::class, array('attr' => array('id' => 'reg_username', 'class' => 'form-control', 'autocomplete' => 'off')))
                ->add('password', RepeatedType::class, array(
                    'type' => PasswordType::class,
                    'invalid_message' => 'The password fields must match.',
                    'options' => array('attr' => array('class' => 'form-control')),
                    'first_options' => array('label' => 'Password'),
                    'second_options' => array('label' => 'Repeat Password'),
                    'required' => true,
                ))
                ->add('submit', SubmitType::class, array('attr' => array('class' => 'btn btn-sm btn-primary', 'style' => 'margin-top:15px;margin:bottom:15px')))
                ->getForm();

I have found some example for symfony 2 and i need something simiar for symfony 3:

// build form
        $formBuilderOne = $this->container
                ->get('form.factory')
                ->createNamedBuilder('formOne', 'form', NULL, array('validation_groups' => array()))
                ->add('name', 'text')
                ->add('submit', 'submit');

        // get form from form builder
        $formOne = $formBuilderOne
                ->getForm()
                ->handleRequest($request);

1 Answer 1

2
public function multiformAction()
{
    $form1 = $this->get('form.factory')->createNamedBuilder($formTypeA, 'form1name')
        ->add('foo', 'text')
        ->getForm();

    $form2 = $this->get('form.factory')->createNamedBuilder($formTypeB, 'form2name')
        ->add('bar', 'text')
        ->getForm();

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

        if ($request->request->has('form1name') {
            // handle the first form
        }

        if ($request->request->has('form2name') {
            // handle the second form
        }
    }

    return array(
        'form1' => $form1->createView(),
        'form2' => $form2->createView()
    );  
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.