title: Symfony2 Doctrine2 postPersist on Associations
body: <p>Is there a way to receive Doctrine lifecycle events in symfony2 for an association field?
  <a href="http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/events.html#lifecycle-events" rel="nofollow">http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/events.html#lifecycle-events</a></p>
  
  <p>for example:</p>
  
  <pre><code>Entity\User.php
  ..
  
   /**
   * @ORM\ManyToMany(targetEntity="Group", inversedBy="users", cascade={"persist"})
   * @ORM\JoinTable(name="users_groups",
   *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")},
   *      inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id", onDelete="CASCADE")}
   * )
   */
  protected $groups;
  </code></pre>
  
  <p>So When I create an event listener for the User Entity
  <a href="http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html" rel="nofollow">http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html</a></p>
  
  <p>The Listener gets called when a Entity\Group is added to the Entity\User.</p>
  
  <p><em><strong>NOTE: The only way I can find of getting this functionality is to create an Entity\UserGroup and monitor that postPersist instead of the Users PostPersist.</em></strong></p>
  
  <p>Is that the only way to listen for associations of entities?</p>
  
  <p><strong>UPDATE ANSWER! 
  The Owner of the Association does get called during the update of the association field but is NOT in the getEntityChangeSet from the Event Args. You have to get the getScheduledCollectionUpdates from the Unit of Work in the Entity Manager. For example:</strong></p>
  
  <pre><code>EventListener\PostEventListener
  ..
  
  public function postUpdate(LifecycleEventArgs $args)
  {
    $this-&gt;handlePostEvents($args);
  }
  
  
  public function postPersist(LifecycleEventArgs $args)
  {
    $this-&gt;handlePostEvents($args);
  }
  
  public function handlePostEvents(LifecycleEventArgs $args){
    $entity = $args-&gt;getEntity();
    $em = $args-&gt;getEntityManager();
  
    if ($entity instanceof User) {
      $uow = $em-&gt;getUnitOfWork();
      foreach ($uow-&gt;getScheduledCollectionUpdates() AS $col) {
        if ($col-&gt;first() instanceof Group) {
          // ADD CODE HERE
        }
      }
    }
  }
  </code></pre>