@mallory_cormier
In Symfony, form submissions can be handled in a controller method. Here are the steps to handle a form submission in Symfony:
Here's an example controller method that handles a form submission:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
use App\Form\ContactType; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/contact", name="contact") */ public function contact(Request $request, Swift_Mailer $mailer) { $form = $this->createForm(ContactType::class); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $data = $form->getData(); // Send email using Swift Mailer $message = (new Swift_Message('Contact form submission')) ->setFrom($data['email']) ->setTo('[email protected]') ->setBody( $this->renderView( 'emails/contact.html.twig', ['data' => $data] ), 'text/html' ); $mailer->send($message); $this->addFlash('success', 'Your message has been sent!'); return $this->redirectToRoute('homepage'); } return $this->render('contact.html.twig', [ 'form' => $form->createView(), ]); } |
In this example, the contact
method handles a form submission for a contact form. It uses the ContactType
form type class to define the form fields, and creates a form instance using the createForm
method. It then handles the form submission using the handleRequest
method.
If the form is valid, the method sends an email using Swift Mailer and redirects the user to the homepage. If the form is not valid, the method re-renders the form with the validation errors.