Symfony -> How to make created and modified fields dynamic with Doctrine? Symfony -> How to make created and modified fields dynamic with Doctrine? symfony symfony

Symfony -> How to make created and modified fields dynamic with Doctrine?


Here my solution after this time ...

You just need to put this directly into your entity class :

/** * @ORM\Entity * @ORM\HasLifecycleCallbacks */class MyEntity {   //....    public function __construct() {        // we set up "created"+"modified"        $this->setCreated(new \DateTime());        if ($this->getModified() == null) {            $this->setModified(new \DateTime());        }    }    /**     * @ORM\PrePersist()     * @ORM\PreUpdate()     */    public function updateModifiedDatetime() {        // update the modified time        $this->setModified(new \DateTime());    }    //....    }

It works well actually


You can use StofDoctrineExtensionsBundle. This describes in symfony cookbook. It contains Timestampable behavior.

/** * @var datetime $created * * @Gedmo\Timestampable(on="create") * @ORM\Column(type="datetime") */private $created;/** * @var datetime $updated * * @Gedmo\Timestampable(on="update") * @ORM\Column(type="datetime") */private $updated;


/** * * @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')));    }}

You dont need to call in __constructor anything. Just create getter and setter properties created, modified and that is all.

If you set first setCreated() on every update you will update also created colum. So put first setModifedAt()