Search code examples
phpdoctrine-ormcallbackannotationspersistence

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

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

/**
 * @PrePersist()
 */
public function populate() {
    $fieldsCollection = new \Doctrine\Common\Collections\ArrayCollection();

    $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?


Solution

  • 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 Doctrine\Common\Persistence\Event\LifecycleEventArgs;
    
    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
            }
        }
    }