Doctrine 2 preFlush Event Add Associated Class

doctrine-orm, events, symfony

Solution

You are computing changesets incorrectly. Following bit:

$meta = $em->getClassMetadata(get_class($entity));
$uow->recomputeSingleEntityChangeSet($meta, $entity);
$uow->computeChangeSets($meta, $entity);

Is executed only on the last entity in the checked context.

You should instead move it to your foreach:

foreach ($uow->getScheduledEntityInsertions() as $entity) {
    $entity->setCreatedBy($user);
    $em->persist($user);

    $meta = $em->getClassMetadata(get_class($entity));

    $uow->recomputeSingleEntityChangeSet($meta, $entity);
}

Even better (since you are not familiar with the `UnitOfWork` API), you could recompute all changesets once at the end only:

foreach ($uow->getScheduledEntityInsertions() as $entity) {
    $entity->setCreatedBy($user);
    $em->persist($user);
}

$uow->computeChangeSets();

You should also move this listener from `preFlush` to `onFlush` to handle any changes applied by other listeners.

Problem

I am trying to add a user entity to an entity on the preFlush event. Basically each entity has a createdBy which is a User entity. Whenever I try this I receive the following error. ``` Notice: Undefined index: 0000000055f036b6000000009c9cc58f in /dir/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 870 ``` This is my preFlush function. ``` public function preFlush(PreFlushEventArgs $args) { $em = $args->getEntityManager(); $uow = $em->getUnitOfWork(); $securityContext = $this->container->get('security.context'); if($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') || $securityContext->isGranted('IS_AUTHENTICATED_FULLY')) { $user = $securityContext->getToken()->getUser(); } if(!$user) { $user = $em->getRepository('NAB\EnterpriseBundle\Entity\User')->findOneByUsername($this->username); } foreach ($uow->getScheduledEntityInsertions() as $entity) { $entity->setCreatedBy($user); $em->persist($user); } $meta = $em->getClassMetadata(get_class($entity)); $uow->recomputeSingleEntityChangeSet($meta, $entity); $uow->computeChangeSets($meta, $entity); } ``` What am I doing wrong?

Original source