I have read the Symfony Documentation on Entity Listeners and Doctrine Documentation on Entity Listeners in addition to this answer and this blog post by Eric Geloen but I can not get my listener to do what I want. In this entity I have a field called status, and when this field changes, an email is going to be sent notifying the receiver of the change.
Entity
I have an entity shipmentLine
with the following annotations:
<?php
namespace Acme\Bundle\ShipmentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
* @ORM\EntityListeners({"\Acme\Bundle\ShipmentBundle\Listener\ShipmentLineListener"})
* @ExclusionPolicy("all")
*/
class ShipmentLine
{
. . .
}
Listener
The ShipmentLineListener has implemented the __construct
and prePersist
functions:
<?php
namespace Acme\Bundle\ShipmentBundle\Listener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Acme\Bundle\ShipmentBundle\Entity\ShipmentLine;
class ShipmentLineListener
{
private $mailer;
private $twig;
public function __construct(\Swift_Mailer $mailer, \Twig_Environment $twig)
{
$this->mailer = $mailer;
$this->twig = $twig;
}
public function prePersist(ShipmentLine $shipmentLine, LifecycleEventArgs $event)
{
/** @var \Swift_Mime_Message $message */
$message = \Swift_Message::newInstance()
->setSubject('Entity Listener test')
->setFrom(array('[email protected]' => 'Acme'))
->setTo(array('[email protected]' => 'Tommy (Acme)'))
->setBody(json_encode($event), 'text/html');
$this->mailer->send($message);
}
}
services.yml
Lastly I have registered my listener in services.yml
entity.entity_listener.shipmentline_update:
class: Acme\Bundle\ShipmentBundle\Listener\ShipmentLineListener
arguments: [ "@mailer", "@twig" ]
tags:
- { name: doctrine.orm.entity_listener, event: prePersist }
The listener fires, and the mail is sent. But both the $shipmentLine
and $event
argument is empty. Can someone see if I do anything wrong? I have a hard time seeing any errors from what I have read.
Thank you for your time.