<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Request;
use Boab\CmsBundle\Controller\BaseController;
use Symfony\Component\Routing\RouterInterface;
use Boab\CmsBundle\Controller\PublicControllerInterface;
use App\Form\ContactType;
use App\Model\Mail;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
class ContactController extends BaseController implements PublicControllerInterface
{
protected $router;
private $appRoot;
protected $entityManager;
public function __construct(RouterInterface $router, EntityManagerInterface $entityManager, $projectDir)
{
$this->router = $router;
$this->appRoot = $projectDir;
$this->entityManager = $entityManager;
}
public function contactAction(Request $request, MailerInterface $mailer)
{
$action = $this->router->generate('contact_us');
$form = $this->createForm(ContactType::class,new Mail, [
'action' => $action,
'method' => 'POST',
]);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$mail = $form->getData();
$this->sendContactMail($mailer, $mail);
//$event = new ContactFormSubmitedEvent($mail);
//$this->eventDispatcher->dispatch($event,'contact.form_submited');
return $this->redirect($this->router->generate('contact_us'));
}
$view = $this->viewManager->load('page/contact_form.html.twig');
$view['form'] = $form->createView();
return new Response($view->render());
}
public function checkContactAction(Request $request, $routeDocument=null, MailerInterface $mailer)
{
$contactForm = $this->createForm(new ContactType(), []);
$contactForm->handleRequest($request);
if($contactForm->isSubmitted() && !$contactForm->isValid()) {
$this->flash->setErrors($this->getFormErrors($contactForm));
return $this->redirect($this->router->generate('contact_us'), 301);
}
$data = $contactForm->getData();
$this->sendContactMail($mailer, $data);
$this->flash->setSuccess('Message sent successfully');
return $this->redirect($this->router->generate('contact_us'));
}
private function sendContactMail($mailer, $mail)
{
$email = (new TemplatedEmail())
->from(new Address('mailer@cmc-ghana.org', 'Contact Form'))
->to('info@cmc-ghana.com')
->subject($mail->getSubject())
->htmlTemplate('mail/contact_message.html.twig')
->context([
"mail"=>$mail
])
;
$mailer->send($email);
}
}