How to set created and updated date in symfony2?

て烟熏妆下的殇ゞ 提交于 2020-01-23 09:33:06

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/28403569/how-to-set-created-and-updated-date-in-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!