Im beginner in Symfony :)
Ive created a website with Symfony 6.And i have a contact form page. This form work great but, after submit, if i reload the page, this form submit again.
Here, the ContactController
#[Route('/contact', name: 'contact')]
public function contact(ManagerRegistry $doctrine, Request $request, MailerInterface $mailer): Response
{
$form = $this->createForm(ContactType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$email = (new Email())
->to("contact@test-test.com")
->from($form->get("email")->getData())
->subject($form->get("title")->getData())
->text('Sending emails is fun again!')
->html('<p>See Twig integration for better HTML integration!</p>');
try {
$mailer->send($email);
$resultMail = "Le mail est envoyé ! Pensez à consulter vos spams.";
$this->addFlash(
"success",
"Votre message est bien envoyé."
);
} catch (TransportExceptionInterface $e) {
// some error prevented the email sending; display an
// error message or try to resend the message
$resultMail = "Il y a eu une erreur lors de l'envoi de l'email.";
$error = new Contact;
$error->setEmail($form->get("email")->getData());
$error->setTitle($form->get("title")->getData());
$error->setMessage($form->get("message")->getData());
$error->setDate(new DateTime());
$error->setError($e);
$em = $doctrine->getManager();
$em->persist($error);
$em->flush();
$this->addFlash(
"error",
"Une erreur s'est produite lors de l'envoi de votre message."
);
}
}
return $this->render('contact/contact.html.twig', [
"pageTitle" => "Contact",
"ssTitle" => "Vous avez besoin de mes services ?",
"contact_form" => $form->createView()
]);
}
How to fix it? And This is possible to redirect to contact anchor after submit ? (/contact#form) ?
Regards
After this snippet of code
$mailer->send($email);
$resultMail = "Le mail est envoyé ! Pensez à consulter vos spams.";
$this->addFlash(
"success",
"Votre message est bien envoyé."
);
you can place something like
return $this->redirectToRoute($routeName);
where $routeName
is the name of the route (not the URL) where you want the user to be redirected if form contains valid data and mail is sent