Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set created and updated date in symfony2?

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.

like image 925
Raaz Avatar asked Feb 09 '15 05:02

Raaz


1 Answers

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

like image 50
Matteo Avatar answered Sep 27 '22 16:09

Matteo