Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

In example below, while we're removing a record from User entity, we're inserting records into UserLog entity.


UserController.php


public function updateAction()
{
$user = $this->userRepository->findOneByUsername('inanzzz');
if ($user instanceof User) {
$this->entityManager->remove($user);
$this->entityManager->flush();
}
}

Listeners.yml


services:
application_backend.event_listener.user_entity:
class: Application\BackendBundle\EventListener\UserEntityListener
tags:
- { name: doctrine.event_listener, event: preRemove }
- { name: doctrine.event_listener, event: postRemove }

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 preRemove(LifecycleEventArgs $args)
{
$entity = $args->getEntity();

if ($entity instanceof User) {
$userLog = new UserLog();
$userLog->setUserId($entity->getId());
$userLog->setMessage('preRemove at ' . date('d/m/Y H:i:s'));

$em = $args->getEntityManager();
$em->persist($userLog);
$em->flush();
}
}

public function postRemove(LifecycleEventArgs $args)
{
$entity = $args->getEntity();

if ($entity instanceof User) {
$userLog = new UserLog();
$userLog->setUserId($entity->getId());
$userLog->setMessage('postRemove at ' . date('d/m/Y H:i:s'));

$em = $args->getEntityManager();
$em->persist($userLog);
$em->flush();
}
}
}

Result


mysql> SELECT id, username, password, pre_update FROM user LIMIT 1;
+----+----------+------------------------------------------+------------+
| id | username | password | pre_update |
+----+----------+------------------------------------------+------------+
| 32 | inanzzz | 09cd68a2a77b22a312dded612dd0d9988685189f | NULL |
+----+----------+------------------------------------------+------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM user_log;
Empty set (0.00 sec)

mysql> SELECT * FROM user WHERE username = 'inanzzz';
Empty set (0.00 sec)

mysql> SELECT * FROM user_log;
+----+---------+-----------------------------------+
| id | user_id | message |
+----+---------+-----------------------------------+
| 10 | 32 | preRemove at 29/06/2015 22:07:55 |
| 11 | NULL | postRemove at 29/06/2015 22:07:55 |
+----+---------+-----------------------------------+
3 rows in set (0.00 sec)