Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding additional persist calls to preUpdate call in Symfony 2.1

I have a preUpdate listener in my app. When it is fired I want it to create some additional records. A simplified example of the basic functionality is below. In this current implementation it would appear that the new events are not being persisted. Are there other calls I need to be making here? Thanks.

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();
}
like image 475
keybored Avatar asked Jun 03 '13 19:06

keybored


1 Answers

The key is to persist them after the 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();
        }
    }
}
like image 180
coma Avatar answered Nov 08 '22 14:11

coma