Symfony2 Entity Timestamps With Doctrine

1. Add line to entity annotation:

@ORM\HasLifecycleCallbacks

2. Add new columns for created and modified:

/**
* @ORM\Column(type="datetime")
*/
protected $created_at;

/**
* @ORM\Column(type="datetime")
*/
protected $modified_at;

3. Now tell doctrine that before persisting or updating, call updatedTimestamps()

/**
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function updatedTimestamps()
{
    $this->setModifiedAt(new \DateTime(date('Y-m-d H:i:s')));

    if($this->getCreatedAt() == null)
    {
        $this->setCreatedAt(new \DateTime(date('Y-m-d H:i:s')));
    }
}

http://www.jamesmandrews.com/2012/10/31/symfony-2-entity-timestamps-with-doctrine/

Leave a Reply

Your email address will not be published. Required fields are marked *