Skip to content
Advertisement

How persist new Entity in Doctrine 2 prePersist method?

I’ve a Entity with @HasLifecycleCallbacks for define prePersist and preUpdate method.

My PrePersist method is

/**
 * @ORMOneToMany(targetEntity="Field", mappedBy="service", cascade={"persist"}, orphanRemoval=true)
 */
protected $fields;

/**
 * @PrePersist()
 */
public function populate() {
    $fieldsCollection = new DoctrineCommonCollectionsArrayCollection();

    $fields = array();
    preg_match_all('/%[a-z]+%/', $this->getPattern(), $fields);
    if (isset($fields[0])) {
        foreach ($fields[0] as $field_name) {
            $field = new Field();
            $field->setField($field_name);
            $field->setService($this);
            $fieldsCollection->add($field);
        }
        $this->setFields($fieldsCollection);
    }
}

I hoped that this could persist my Field entities, but my table is empty. Should I use an EntityManager? How can I retrieve it within my Entity?

Advertisement

Answer

You need to use the LifecycleEventArgs to get EntityManager and be able to persist Entity in prePersist method. You can retrieve it like that :

<?php
use DoctrineCommonPersistenceEventLifecycleEventArgs;

class MyEventListener
{
    public function preUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();
        $entityManager = $args->getObjectManager();

        // perhaps you only want to act on some "Product" entity
        if ($entity instanceof Product) 
        {
            // do something with the Product
        }
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement