2013-06-03 8 views
11

Ho un listener preUpdate nella mia app. Quando viene sparato, voglio che crei dei record aggiuntivi. Di seguito è riportato un esempio semplificato della funzionalità di base. In questa attuale implementazione sembrerebbe che i nuovi eventi non vengano mantenuti. Ci sono altre chiamate che devo fare qui? Grazie.Aggiunta di ulteriori chiamate persistenti alla chiamata preUpdate in Symfony 2.1

public function preUpdate(Event\LifecycleEventArgs $eventArgs) 
{ 
    $em = $eventArgs->getEntityManager(); 
    $uow = $em->getUnitOfWork(); 
    $entity = $eventArgs->getEntity(); 

    $updateArray = $eventArgs->getEntityChangeSet(); 

    //Updates 
    if (($entity instanceof Bam) === false) { 
     $thing = new OtherThing(); 
     $thing->setFoo('bar'); 

     $uow->persist($thing); 
    } 

    $uow->computeChangeSets(); 
} 
+0

Qual è '$ historyRecord'? – cheesemacfly

+0

Errore di battitura, corretto. – keybored

risposta

26

La chiave è di persistere loro dopo il flush:

<?php 

namespace Comakai\CQZBundle\Handler; 

use Symfony\Component\DependencyInjection\ContainerInterface; 
use Doctrine\Common\EventSubscriber; 
use Doctrine\ORM\Event; 

/** 
* 
*/ 
class YourHandler implements EventSubscriber 
{ 
    protected $things = []; 

    public function getSubscribedEvents() 
    { 
     /** 
     * @todo Check if this is running in the console or what... 
     */ 
     if (isset($_SERVER['HTTP_HOST'])) { 

      return [ 
       'preUpdate', 
       'postFlush' 
      ]; 
     } 

     return []; 
    } 

    public function preUpdate(Event\LifecycleEventArgs $eventArgs) 
    { 
     $em = $eventArgs->getEntityManager(); 
     $uow = $em->getUnitOfWork(); 
     $entity = $eventArgs->getEntity(); 

     $updateArray = $eventArgs->getEntityChangeSet(); 

     //Updates 
     if (($entity instanceof Bam) === false) { 

      $thing = new OtherThing(); 
      $thing->setFoo('bar'); 

      $this->things[] = $thing; 
     } 
    } 

    public function postFlush(Event\PostFlushEventArgs $event) 
    { 
     if(!empty($this->things)) { 

      $em = $event->getEntityManager(); 

      foreach ($this->things as $thing) { 

       $em->persist($thing); 
      } 

      $this->things = []; 
      $em->flush(); 
     } 
    } 
} 
+1

Provo questo, ma ho "Errore Fatal PHP: raggiunto il livello massimo di nidificazione delle funzioni di" 1000 "," –

+2

Rileva bug: è molto importante impostare "$ this-> things = [];" prima di "$ em-> flush();" –

+0

Scusa, è successo anche a me !, aggiornando la mia risposta, grazie Igor. – coma

Problemi correlati