<?php
namespace App\Controller\Front;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mime\Address;
class ContactController extends AbstractController
{
/**
* @Route ("/contact", name="app_main_contact", methods={"GET"})
*/
public function contactAction(): Response
{
return $this->render('Main/contact.html.twig');
}
/**
* @Route("/contact-ajax", name="app_main_contact_ajax", methods={"POST"})
*/
public function contactajaxAction(Request $request, MailerInterface $mailer): Response
{
if ($request->getMethod() == 'POST') {
// Send headers
header('HTTP/1.1 200 OK');
header('Status: 200 OK');
header('Content-type: application/json');
$message = $request->request->get('message');
$the_mail =$request->request->get('email');
$name =$request->request->get('name');
$nonValid = array();
// Check if fields are valid
if(empty($the_mail) || !filter_var($the_mail, FILTER_VALIDATE_EMAIL)) $nonValid[] = "email";
if(empty($name)) $nonValid[] = "name";
if(empty($message)) $nonValid[] = "message";
// If some of them are not valid then return error
if(!empty($nonValid)) {
return new Response (json_encode(array(
"status" => "error",
"type" => "ValidationError",
"fields" => $nonValid
)));
}
$email = (new TemplatedEmail())
->from('sharjah.masjids@gmail.com')
->to('sharjah.masjids@gmail.com')
->subject('sharjah-masjids.com')
// path of the Twig template to render
->htmlTemplate('mail/contact_form.html.twig')
// pass variables (name => value) to the template
->context([
'mess' => $message,
'name' => $name,
'the_mail' => $the_mail,
])
;
try {
$mailer->send($email);
} catch (TransportExceptionInterface $e) {
// some error prevented the email sending; display an
// error message or try to resend the message
}
return new Response(json_encode(array(
"status" => "success"
)));
}
else {
new Response (json_encode(array(
"status" => "error",
"type" => "SendingError"
)));
}
}
}