Skip to content

Instantly share code, notes, and snippets.

@webdevilopers
Last active March 11, 2020 09:00
Show Gist options
  • Save webdevilopers/4eea317ade72a119a72e to your computer and use it in GitHub Desktop.
Save webdevilopers/4eea317ade72a119a72e to your computer and use it in GitHub Desktop.
Symfony Event Listener to send html mail using SwiftMailer and Twig
<?php
namespace Acme\Bundle\ContractBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class ContractController extends Controller
{
public function eventAction(Contract $contract)
{
$event = new ContractEvent($contract);
$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch(
ContractEvents::CONTRACT_CREATED,
$event
);
return $this->render('AcmeContractBundle:Contract:index.html.twig', array(
'contract' => $contract
));
}
}
<?php
namespace Acme\Bundle\ContractBundle\Event;
use Symfony\Component\EventDispatcher\Event;
use Acme\Bundle\ContractBundle\Entity\Contract;
class ContractEvent extends Event
{
protected $contract;
public function __construct(Contract $contract)
{
$this->contract = $contract;
}
public function getContract()
{
return $this->contract;
}
}
<?php
namespace Acme\Bundle\ContractBundle;
final class ContractEvents
{
const CONTRACT_CREATED = 'contract.created';
}
<?php
namespace Acme\Bundle\ContractBundle\Event;
use Acme\Bundle\ContractBundle\Event\ContractEvent;
class ContractListener
{
protected $twig;
protected $mailer;
public function __construct(\Twig_Environment $twig, \Swift_Mailer $mailer)
{
$this->twig = $twig;
$this->mailer = $mailer;
}
public function onContractCreated(ContractEvent $event)
{
$contract = $event->getContract();
$body = $this->renderTemplate($contract);
$projectManager = $contract->getProjectManager();
$message = \Swift_Message::newInstance()
->setSubject('Contract ' . $contract->getId() . ' created')
->setFrom('[email protected]')
->setTo('[email protected]')
->setBody($body)
;
$this->mailer->send($message);
}
public function renderTemplate($contract)
{
return $this->twig->render(
'AcmeContractBundle:Contract:mailer.html.twig',
array(
'contract' => $contract
)
);
}
}
services:
contract_bundle.listener.contract:
class: Acme\Bundle\ContractBundle\Event\ContractListener
arguments:
templating: "@twig"
mailer: "@mailer"
tags:
- { name: kernel.event_listener, event: contract.approved, method: onCommentEvent }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment