this is my first question so please bear with me.
How can I implement a postPersist Event Listener to update a log table when creating or updating an order in the order table using Sonata.
I understand how to use a prePersist to add information to the same database table as soon as I create a new order. (See the following code snippet)
public function prePersist(LifecycleEventArgs $args)
{
$order = $args->getEntity();
if ($order instanceof PmodOrder) {
$user = $this->serviceContainer->get('security.token_storage')->getToken()->getUser();
if ($user) {
$order->setCreatedBy($user);
$order->setCreatedAt(new \DateTime(date('Y-m-d H:i:s')));
}
}
}
But I don't fully understand how I would do this when updating another table, because it is not the same entity.
The moment an order is created, (I think) a postPersist should update another table with that order's ID and some extra information.
I think something between the lines like this;
public function postPersist(LifecycleEventArgs $args)
{
$log = $args->getEntity();
if ($log instanceof PmodLog) {
$order = ....;
$user = $this->serviceContainer->get('security.token_storage')->getToken()->getUser();
$department = $this->serviceContainer->get('security.token_storage')->getToken()->getUser()->getDepartment();
if ($order) {
$log->setOrder($order);
$log->setCreatedBy($user);
$log->setCreatedAt(new \DateTime(date('Y-m-d H:i:s')));
$log->setDepartment($department);
$log->setAction("created");
}
}
}
I don't get how to get the current order I'm busy with. And how the setAction will be something else when the user modified the order. For example 'edited' or 'approved'. I've been trough the documentation of Sonata with no luck unless I miss read something.
Remember I use Sonata, otherwise this would've been easy to implement in my own Controller Actions.
You can directly add to your entity a listener that create/update your order's logs.
First you create the listener class :
use Doctrine\ORM\Event\LifecycleEventArgs;
class OrderListener
{
public function postPersist(Order $order, LifecycleEventArgs $event)
{
// for example
// if you want to store the date creation :
if($order->getId() == null)
{
$order->setDateCreate(new \DateTime('now'));
}
// if you want to store the last update date :
$order->setDateUpdate(new \DateTime('now'));
//... or whatever you want to store...
}
}
Then register it in a service.yml :
order_listener:
class: YOUR\NAMESPACE\OrderListener
tags:
- { name: doctrine.orm.entity_listener }
Finally, link your entity to the listener (here with annotations) :
/**
* @ORM\EntityListener("YOUR\NAMESPACE\OrderListener")
*/
class Order
{
...
}