Reputation:
I have a system where a user can create an order. As soon as the order is created another entity table should be updated with the current user who created the order, the time he created it, and some other information.
Basically a Log.
Here is my Listener class;
namespace Qi\Bss\BaseBundle\Lib\PurchaseModule;
use Qi\Bss\BaseBundle\Entity\Business\PurchaseModule\PmodLog;
use Qi\Bss\BaseBundle\Entity\Business\PurchaseModule\PmodOrder;
use Doctrine\ORM\Event\LifecycleEventArgs;
/**
* Class OrderLogger. Purchase Module activity logger.
*/
class OrderLogger
{
/**
* Service container
* @var type
*/
private $serviceContainer;
/**
* Performs tasks before destruction
* @ORM\PostPersist
*/
public function postPersist(LifecycleEventArgs $args)
{
$order = $args->getEntity();
if ($order instanceof PmodOrder) {
$logRecord = new PmodLog();
$user = $this->serviceContainer->get('security.token_storage')->getToken()->getUser();
$logRecord->setCreatedBy($user);
$logRecord->setAction('Gemaak');
$logRecord->setCreatedAt(new \DateTime());
$logRecord->setOrder($order);
$logRecord->setDepartment($user->getDepartment());
}
}
/**
* Sets the sales order exporter object
* @param type $serviceContainer
*/
public function setServiceContainer($serviceContainer)
{
$this->serviceContainer = $serviceContainer;
}
}
I don't get what I'm doing wrong and that the log table in my database doesn't get updated whatsoever.
Here is my service as well;
bss.pmod.logger:
class: Qi\Bss\BaseBundle\Lib\PurchaseModule\OrderLogger
calls:
- [ setServiceContainer, [@service_container] ]
tags:
- { name: doctrine.event_listener, event: postPersist }
I don't get an error, the order is perfectly created but the log database remain empty.
Upvotes: 1
Views: 2265
Reputation: 12730
You can adapt this to yours. Right after someone creates a User
entity, a new UserLog
entity/record gets created by inserting some data from User
entity as well.
Controller
public function createAction()
{
$user = new User();
$user->setUsername('username');
$user->setPassword('password');
$this->entityManager->persist($user);
$this->entityManager->flush();
}
Services.yml
services:
application_backend.event_listener.user_entity:
class: Application\BackendBundle\EventListener\UserEntityListener
tags:
- { name: doctrine.event_listener, event: postPersist }
UserEntityListener.php
namespace Application\BackendBundle\EventListener;
use Application\BackendBundle\Entity\User;
use Application\BackendBundle\Entity\UserLog;
use Doctrine\ORM\Event\LifecycleEventArgs;
class UserEntityListener
{
public function postPersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof User) {
$log = new UserLog();
$log->setUserId($entity->getId());
$log->setMessage('postPersist at ' . date('d/m/Y H:i:s'));
$em = $args->getEntityManager();
$em->persist($log);
$em->flush();
}
}
}
Upvotes: 1
Reputation: 2597
Well don't you need to persist and flush $logRecord
? You can get the entity manager from $args
.
Upvotes: 1