title: Doctrine 2 preFlush Event Add Associated Class
body: <p>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.  </p>
  
  <p>Whenever I try this I receive the following error. </p>
  
  <pre><code>Notice: Undefined index: 0000000055f036b6000000009c9cc58f in /dir/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 870 
  </code></pre>
  
  <p>This is my preFlush function.  </p>
  
  <pre><code>public function preFlush(PreFlushEventArgs $args)
  {
      $em = $args-&gt;getEntityManager();
      $uow = $em-&gt;getUnitOfWork();
      $securityContext = $this-&gt;container-&gt;get('security.context');
      if($securityContext-&gt;isGranted('IS_AUTHENTICATED_REMEMBERED') 
          || $securityContext-&gt;isGranted('IS_AUTHENTICATED_FULLY'))
      {
          $user = $securityContext-&gt;getToken()-&gt;getUser();
      }
      if(!$user)
      {
          $user = $em-&gt;getRepository('NAB\EnterpriseBundle\Entity\User')-&gt;findOneByUsername($this-&gt;username);
      }
      foreach ($uow-&gt;getScheduledEntityInsertions() as $entity)
      {
          $entity-&gt;setCreatedBy($user);
          $em-&gt;persist($user);
  
      }
      $meta = $em-&gt;getClassMetadata(get_class($entity));
      $uow-&gt;recomputeSingleEntityChangeSet($meta, $entity);
      $uow-&gt;computeChangeSets($meta, $entity);
  }
  </code></pre>
  
  <p>What am I doing wrong?</p>