tags:

views:

52

answers:

1

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());
}
+2  A: 

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());
}
rojoca
Thanks - I considered creating 2 methods and doing it this way, but I can live with one. I just wasn't sure if preUpdate was legitimately only for updates, or both inserts and updates.
Harold1983-