How to handle form submissions in Symfony?

by mallory_cormier , in category: PHP Frameworks , a year ago

How to handle form submissions in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , a year ago

@mallory_cormier 

In Symfony, form submissions can be handled in a controller method. Here are the steps to handle a form submission in Symfony:

  1. Create a form type class that defines the fields of the form and their validation rules. You can generate a form type class using the make:form command in the console, or create it manually.
  2. Create a controller method that renders the form and handles its submission. The controller method should have two parts: one for rendering the form, and another for handling the form submission. You can use the createForm method to create a form instance, and the handleRequest method to handle the form submission.
  3. In the form submission handler, you can check if the form is valid using the isSubmitted and isValid methods. If the form is valid, you can process the form data and redirect the user to another page. If the form is not valid, you can re-render the form with the validation errors.


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.