src/Controller/ContactController.php line 18

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Form\ContactFormType;
  4. use App\Model\Contact;
  5. use App\Service\MailService;
  6. use Exception;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\Routing\Annotation\Route;
  11. #[Route('/contact')]
  12. class ContactController extends AbstractController
  13. {
  14. #[Route('/', name: 'app_contact_index')]
  15. public function index(Request $request, MailService $mailService): Response
  16. {
  17. $contact = new Contact();
  18. $form = $this->createForm(ContactFormType::class, $contact);
  19. $form->handleRequest($request);
  20. if ($form->isSubmitted() && $form->isValid()) {
  21. try{
  22. $contact = $form->getData();
  23. $recipient = $this->getParameter('contact_recipient_mail');
  24. if (!is_string($recipient) || trim($recipient) === '') {
  25. throw new Exception('Environment variable not found: "CONTACT_RECIPIENT_MAIL"');
  26. }
  27. $mail = [
  28. 'to' => $recipient,
  29. 'subject' => "Nouveau contact de ".$contact->getName(),
  30. 'body' => $mailService->renderTwig('emails/contact.html.twig', ['contact' => $contact])
  31. ];
  32. $mailService->sendMail($mail);
  33. $this->addFlash('success', 'Message envoyé');
  34. } catch(\Exception $ex){
  35. $this->addFlash('danger', $ex->getMessage());
  36. }
  37. }
  38. return $this->render('contact/contact_index.html.twig', [
  39. 'form' => $form->createView(),
  40. 'contact' => $contact
  41. ]);
  42. }
  43. }