Symfony2 / SonataAdminBundle / Sending email after record edit
I need to send an email based on a template after I have edited a post using SonataAdminBundle.
On a regular site, I send an email to the controller. Something like that:
$message = \Swift_Message::newInstance()
->setContentType('text/html')
->setSubject('Subject')
->setFrom('from@site.com')
->setTo($member->getEmail())
->setBody(
$this->renderView(
'AcmeSiteBundle:Site:email.html.twig',
array('name' => $member->getFirstName())
)
)
;
$this->get('mailer')->send($message);
But in admin I configure configureFormFields, preUpdate, postUpdate methods of MyAdmin that propagate from Admin.
+3
source to share
1 answer
And this is the solution: use an EventListener.
Create AdminApplicationListener.php file in VendorName / SiteBundle / EventListener with this code:
<?php
namespace VendorName\SiteBundle\EventListener;
class AdminApplicationListener
{
/**
*
* @var Swift_Mailer
*/
private $__mailer = null;
private $__templating = null;
public function __construct(\Swift_Mailer $mailer, $templating)
{
$this->__mailer = $mailer;
$this->__templating = $templating;
}
public function onApplication( \Sonata\AdminBundle\Event\PersistenceEvent $event )
{
$ac = $event->getObject();
$message = \Swift_Message::newInstance()
->setContentType('text/html')
->setSubject('[VendorName] Object was edited')
->setFrom('admin@VendorName.ru')
->setTo($ac->getEmail())
->setBody(
$this->__templating->render(
'VendorNameSiteBundle:Admin:email.html.twig',
array('name' => $ac->getFirstName())
)
)
;
$this->__mailer->send($message);
}
}
In VendorName / SiteBundle / Resources / config / services.yml add this:
services:
vendor_name.admin.on_application:
class: VendorName\SiteBundle\EventListener\AdminApplicationListener
arguments:
mailer: @mailer
templating: @templating
tags:
- { name: kernel.event_listener, event: sonata.admin.event.persistence.post_update, method: onApplication }
I think this is not the best practice, but for the first step to it it is ok :)
+4
source to share