Home » Php » php – How to set created and updated date in symfony2?

php – How to set created and updated date in symfony2?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am creating a todo app where the user can create tasks.The user has the options of inserting title, due date, completed. I want to be able to insert created and updated date automatically when the user creates the task.

How to&Answers:

A better solution is to use the Timestampable extension for Doctrine from gedmo:
https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/timestampable.md.

This extension uses lifecyclecallbacks, but it is a cleaner way to set created and updated timestamps.

Answer:

You can set created date at the initialisation of an object (in __construct() method) and update date with Doctrine2 Event managed by the LifeCycle callbacks, here is an example:

<?php
namespace Acme\DemoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;


/**
 * @ORM\Entity()
 * @ORM\Table(name="task")
 * @ORM\HasLifecycleCallbacks
 */
class Task {

....

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

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

...

    public function __construct()
    {
        $this->createdAt= new \DateTime();
        $this->updatedAt= new \DateTime();
    }

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

....

}

Hope this help