Using LifecycleCallbacks for CreatedAt and UpdatedAt in Symfony 2

It's a life cycle. *Tumbleweed*

[Update: May 2015 – This post has been updated with videos]

Lifecycle Callbacks are a super helpful bit of code that I use in a good number of my entities.

They are scary sounding and the documentation on the Symfony 2 official docs doesn’t give a detailed enough demonstration (in my opinion) to explain to the new Symfony user how useful they are.

So, rather than waffle on, I will give a bit of handy code that you can steal and re-use.

namespace MCM\MyExampleBundle\Entity;

// some use statements here

/**
 * MyPretendEntity
 *
 * @ORM\Table(name="my_table_name")
 * @ORM\Entity(repositoryClass="\MCM\MyExampleBundle\Repository\MyPretendRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class MyPretendEntity
{
    // snip snip snip

    /**
     * created Time/Date
     *
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=false)
     */
    protected $createdAt;

    /**
     * updated Time/Date
     *
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", nullable=false)
     */
    protected $updatedAt;

    // snip snip snip

    /**
     * Set createdAt
     *
     * @ORM\PrePersist
     */
    public function setCreatedAt()
    {
        $this->createdAt = new \DateTime();
        $this->updatedAt = new \DateTime();
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @ORM\PreUpdate
     */
    public function setUpdatedAt()
    {
        $this->updatedAt = new \DateTime();
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
}

I have seen this done other ways – some people use only one method for both.

The implementation is up to you – but do remember to use the correct annotations – @ORM\HasLifecycleCallbacks() , @ORM\PrePersist , and @ORM\PreUpdate.

There are some other events you can interact with, so be sure to check out the official docs – they become much more useful now that you understand how they work.

Be Sociable, Share!

8 thoughts on “Using LifecycleCallbacks for CreatedAt and UpdatedAt in Symfony 2”

  1. Hi, I’m using this exactly method but my PreUpdate event is not triggered when I update an entity (from my controller by the ‘persist’ and ‘flush’ methods) unlike the PrePersist event that is triggered properly! What am I missing? Thanks 🙂

    1. Is this on a form with an attachment by any chance? If your entity has been changed in some way, the update callback should be triggered.

      However, if you are saving a form that has file attachments, then they don’t always work as expected – can you post up some sample code?

  2. I was looking for the cause of an error message in an entity class, and by reading your code I found that it was caused by a missing class annotation “@ORM\HasLifecycleCallbacks() ” (which it leads to ignore the preUpdate method)… and change the arguments of setCreatedAt and setUpdatedAt from “date(‘Y-m-d H:m:s’)” to “new new \DateTime()” solved another Doctrine error I had, thanks so much for the explanation!

Leave a Reply

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

This blog is kept spam free by WP-SpamFree.