Submit two unrelated forms made on one page

Is there a way to insert two forms (data on 2 unrelated objects) on one page and submit the form with only one submit button?

The idea is to check both submitted forms in only one controller action.

Entity1 and Entity2 have absolutely nothing in common.

|-------------------------- | Form 1 (Entity 1) | |-------------------------- --------------- | | Main Form |------------------ --------------- | |-------------------------- | Form 2 (Entity 2) | |-------------------------- 

Does anyone know if this is possible?

Many thanks.

+4
source share
2 answers

It is possible. Something like this should work:

 $entity1 = new Entity1(); $entity2 = new Entity2(); $form = $this->createMainForm(); $form->setData(array( 'entity1' => $entity1, 'entity2' => $entity2, )); if ($request->isMethod('POST')) { $form->bindRequest($request); if ($form->isValid()) { // $entity1 and $entity2 should contain the post data // and can be persisted or whatever it is you want to do // ... 

You can also create a model that contains both objects and create a shape for it. Using $mainEntity->getEntity1(); to return an object with encapsulation.

+2
source

Symfony 3.20

When you create your FormType, in the controller, follow the route and actions as shown below, use "if ($ formRegister-> isSubmitted () && $ formRegister-> getClickedButton ('form2') & & ...)"

 class WelcomeController extends Controller { /** * @Route("/welcome", name="welcome") */ public function welcomeAction(Request $request) { $uLogin = new User(); $formLogin = $this->createForm(LoginUserFormType::class, $uLogin); $uRegister = new User(); $formRegister = $this->createForm(UserRegistrationFormType::class, $uRegister); $authenticationUtils = $this->get('security.authentication_utils'); $error = $authenticationUtils->getLastAuthenticationError(); // last username entered by the user $lastUsername = $authenticationUtils->getLastUsername(); if ($request->isMethod('post')){ $formLogin->handleRequest($request); $formRegister->handleRequest($request); if($formLogin->isSubmitted() && $formLogin->getClickedButton('form1')){ return $this->redirectToRoute('login_success'); } if ($formRegister->isSubmitted() && $formRegister->getClickedButton('form2') && $formRegister->isValid() ) { $password = $this->get('security.password_encoder') ->encodePassword($uRegister, $uRegister ->getPlainPassword()); $uRegister ->setPassword($password); $uRegister->setRole('ROLE_USER'); $em = $this ->getDoctrine() ->getManager(); $em -> persist($uRegister); $em -> flush(); return $this->redirectToRoute('register_success'); } } return $this->render( 'form/welcome.html.twig', array( 'form1' => $formLogin -> createView(), 'form2' => $formRegister -> createView(), 'last_username' => $lastUsername, 'error' => $error, ) ); } 

Create your own routing, and that is it :-)

0
source

Source: https://habr.com/ru/post/1498922/


All Articles