简体   繁体   中英

Symfony2, set default value of datetime field

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 !

You do it in constructor.

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

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

Set it in your form builder like this :

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

or in your entity constructor

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"})

The property could only be constant value.

If you don't want to do $myEntity->setTimestamp(new \\DateTime('now')); every time, then you could use doctrine lifecycle callbacks to deal it.

if You want to set a default value for the $timestamp make a _contruct in your entity so that each time you declare the object for this entity the value for $timestamp is automatically set.

if you dont want to do this then you have to set the value in your controller and then persist the vlaue in DB. Symfony2 expects a value for each field of DB table.

I'm using Symfony3 and I'm updating the field and options in the orm.xml file for this solution.

<field name="updated_from" type="datetime" nullable="true" >
    <options>
        <option name="default">CURRENT_TIMESTAMP</option>
    </options>
</field>

** btw, I tried to add this annotation to entity also but it didn't work to me! for example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM