Symfony2, set default value of datetime field

18,839

Solution 1

You do it in constructor.

public function __construct(){
    $this->timestamp(new \DateTime());
}

Solution 2

LifecycleCallbacks way:

<?php

use Doctrine\ORM\Mapping as ORM;

/**
 * Example
 *
 * @ORM\Table(name="examples")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class Example
{

    // ...

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="create_at", type="datetime", nullable=false)
     */
    private $createdAt;

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

    // ...

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @ORM\PrePersist
     * @return Example
     */
    public function setCreatedAt()
    {

        if(!$this->createdAt){
            $this->createdAt = new \DateTime();
        }

        return $this;
    }

    // ...

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     * @ORM\PrePersist
     * @return Example
     */
    public function setUpdatedAt()
    {
        $this->updatedAt = new \DateTime();

        return $this;
    }

    // ...
}

Pay attention to the annotations @ORM\HasLifecycleCallbacks and @ORM\PrePersist. Details: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#lifecycle-callbacks

Solution 3

You can do it by adding options to definition and I think it is a better solution for readability. Also, when using a constructor, you should add default to existing rows by with extra calls.

@ORM\Column(name="creation_date", type="datetime", options={"default"="CURRENT_TIMESTAMP"})

Solution 4

Set it in your form builder like this :

$builder->add('timestamp', 'date', array(
    'data' => new \DateTime('now')
));

or in your entity constructor

Share:
18,839
Clément Andraud
Author by

Clément Andraud

I'm a wonderful dev !

Updated on June 04, 2022

Comments

  • Clément Andraud
    Clément Andraud almost 2 years

    So, i have in my entity a DateTime field like that :

    /**
         * @var \DateTime
         *
         * @ORM\Column(name="timestamp", type="datetime")
         */
        private $timestamp;
    

    Each time i insert something in my database, i do this : $myEntity->setTimestamp(new \DateTime('now'));

    So, i want to set the default value NOW on my field in my entity, but when i try :

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="timestamp", type="datetime")
     */
    private $timestamp = new \DateTime('now');
    

    and after update my base with doctrine:schema:update i have this error : PHP Parse error: syntax error, unexpected 'new' (T_NEW) in...

    How can i set a default value for this field ? I don't want to setTimestamp each time i use my entity... Thanks !