Home » Php » php – Doctrine 2 preUpdate event – not triggered on insert?

php – Doctrine 2 preUpdate event – not triggered on insert?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have a bunch of entities with both a date_created and date_modified field, and I’m attempting to have these fields automatically set themselves on insert or update. date_created is only set at insert, but date_modified is set at both insert or update.

I have a method in my entity class with a @PreUpdate annotation, but it only seems to get called when an entity is updated. It is not called when a new entity is inserted. The documentation says this about the preUpdate event:

“The preUpdate event occurs before the database update operations to entity data.”

Is this correct behavior? If so, what is the best way to have a method called before both update or insert? Currently if I tag the method with both @PreUpdate and @PrePersist then it works, but I’m not sure if this is optimal:

/**
 * @PreUpdate
 * @PrePersist
 */
public function beforeSave()
{
    if (!$this->getCreatedAt()) {
        $this->setCreatedAt(new \DateTime());
    }
    $this->setModifiedAt(new \DateTime());
}
How to&Answers:

Persist and Update are 2 different events so if you want the callback to be applied for them both then you’ll need both annotations. It may satisfy your misgivings to instead create two methods:

/**
 * @PrePersist
 */
public function beforePersist()
{
    $this->setCreatedAt(new \DateTime());        
    $this->setModifiedAt(new \DateTime());
}

/**
 * @PreUpdate
 */
public function beforeUpdate()
{        
    $this->setModifiedAt(new \DateTime());
}