BetaRide
BetaRide

Reputation: 16844

Update "updated" property every time a property has been changed

My doctrine entity has a datetime property called updated. This should get the current time everytime (changed) values of the object are written to the DB. I know how to do this in MySql, but I'm looking for a doctrine/symfony solution.

Is there a way to

  1. hook into something before an INSERT/UPDATE of an instance is sent to the DB.
  2. update the updated property to the current time and make sure it's written to the DB without triggering a second UPDATE statement.

Upvotes: 1

Views: 731

Answers (2)

Tom Imrei
Tom Imrei

Reputation: 1544

You don't need any extensions, just use Lifecycle Callbacks. Basically, mark your entity that it has event callbacks configured with the HasLifecycleCallbacks annotation:

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * ...
 */
class MyEntityClass {
...

And then mark instance methods to be run on specific events occuring, e.g. to set updated:

...
class MyEntityClass {
...
    /**
     * @ORM\PreUpdate
     */
    public function onPreUpdate() {
        $this->updated = new \DateTime();
    }
...

Upvotes: 1

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44841

See the Timestampable behavior of DoctrineExtensions. There is StofDoctrineExtensionsBundle to intergrate it into Symfony.

Upvotes: 5

Related Questions