Doctrine 2 preUpdate event - doesn't fire on insert?

I have a bunch of entities with date_created and date_modified fields, and I'm trying to automatically set these fields to insert or update. date_created is set only in insert, but date_modified is set in both insert and update.

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

"The preUpdate event occurs before database update operations with entity data.

Is this the right behavior? If so, what is the best way to call before updating or pasting? Currently, if I tag a 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()); } 
+6
php doctrine
source share
1 answer

Persist and Update are two different events, so if you want the callback applied to them, you will need both annotations. It can satisfy your concerns, instead create two methods:

 /** * @PrePersist */ public function beforePersist() { $this->setCreatedAt(new \DateTime()); $this->setModifiedAt(new \DateTime()); } /** * @PreUpdate */ public function beforeUpdate() { $this->setModifiedAt(new \DateTime()); } 
+9
source share

All Articles