Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting element in doctrine listener

I have setup a doctrine listener which is fired on different database actions and creates a log entity and insert it into the database.

class FOO { 
 // [...]
 public function onFlush(OnFlushEventArgs $args)
 {
     foreach ($args->getEntityManager()->getUnitOfWork()->getScheduledEntityUpdates() as $entity) {
                $this->createLog('edit', $entity);
     }
 }


 private function createLog($action, $entity)
 {
        if ($entity instanceof Log) {
            return;
        }
        $log = new Log;
        $log->setAction($action);
        $log->setTime(new \DateTime);
        $log->setForeignId($entity->getId());
        $log->setUser($this->getUser());
        $t            = explode('\\', get_class($entity));
        $entity_class = strtolower(end($t));
        $log->setEntity($entity_class);
        $this->getEntityManager()->persist($log);
  }
// [...]
}

When I update an object, I get the following error:

SQLSTATE[HY093]: Invalid parameter number: no parameters were bound

In the profiler I see this query:

INSERT INTO vvg_logs (action, entity, foreign_id, user_id, time) VALUES (?, ?, ?, ?, ?)

Parameters: { }

How could I resolve this problem?

UPDATE Here is my new topic connecting to this question: LINK

like image 454
David Frank Avatar asked Feb 22 '23 06:02

David Frank


1 Answers

Because when onFlush is called, all changes are already calculated and you need to refresh them if you change your entity or create a new entity.

$em = $this->getEntityManager();
$uow = $em->getUnitOfWork();
$logMetadata = $em->getClassMetadata('Your\LogClass');
...
$em->persist($log);
$uow->computeChangeSet($logMetadata, $log);

For postPersist:

$em = $this->getEntityManager();
$uow = $em->getUnitOfWork();
$log = new Log;
...

$logMetadata = $em->getClassMetadata('Your\LogClass');
$className = $logMetadata->name;
$persister = $this->getEntityPersister($className);
$persister->addInsert($log);
$uow->computeChangeSet($classMeta, $logEntry);
$postInsertIds = $persister->executeInserts();

if ($postInsertIds) {
    foreach ($postInsertIds as $id => $entity) {
        $idField = $logMetadata->identifier[0];
        $logMetadata->reflFields[$idField]->setValue($entity, $id);
        $this->addToIdentityMap($entity);
    }
}
like image 105
meze Avatar answered Feb 28 '23 02:02

meze