Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 PrePersist doesn't fire

Within the same entity I have a PreUpdate and a PrePersist. The PreUpdate fires, but the PrePersist never does. I put a die() after the flush and comments within the lifecycle callbacks. Full entity can be seen at http://pastebin.com/yUk1u4GQ

Entity callbacks

/** * @PreUpdate */ public function fixDates(){     $this->updatedOn = $this->getNow();     $this->closedDate = null;     $this->openDate = null;     print "dates fixed"; }  /** * @PrePersist */ public function prePersist() {     print 'in prePersist';     die(); } 

Entity Manager calls

$em->persist($school);  $em->flush(); die(); 

My screen reads "dates fixed", but not the prePersist message. I do have the @HasLifecycleCallbacks at the top of the entity.

like image 456
Tom Avatar asked Oct 28 '11 20:10

Tom


2 Answers

Don't forget to enable Lifecycle Callbacks in your class annotation :

/**  * Report\MainBundle\Entity\Serveur  * @ORM\HasLifecycleCallbacks  */ class Serveur { 
like image 139
Thierry Daguin Avatar answered Sep 28 '22 00:09

Thierry Daguin


PrePersist is fired only when you are performing INSERT statement, not UPDATE statement.

When testing, don't forget that the UPDATE statement is fired only when the entity attributes really change. If the Entity Manager is being called to persist that entity, it first looks if there are any changes. If not, no sql query is performed and no @PreUpdate method is called.

like image 45
Johan Avatar answered Sep 27 '22 23:09

Johan