Doctrine 2.1 - datetime column default value
You map your property as DateTime type then set the value in the constructor using a new DateTime instance:
/**
* @Entity
* @Table(name="...")
*/
class MyEntity
{
/** @Column(type="datetime") */
protected $registration_date;
public function __construct()
{
$this->registration_date = new DateTime();
}
}
This works as the constructor of a persisted class is not called upon hydration.
You can also use lifecycle callbacks if you want to be very precise:
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\HasLifecycleCallbacks
* ...
*/
class MyEntity
{
/**
* @ORM\PrePersist
*/
public function onPrePersistSetRegistrationDate()
{
$this->registration_date = new \DateTime();
}
}
For default value CURRENT_TIMESTAMP:
@ORM\Column(name="created_at", type="datetime", options={"default": "CURRENT_TIMESTAMP"})
Or for older Symfony versions:
@ORM\Column(name="created_at", type="datetime", options={"default": 0})
Worked for me... However this works only with MySQL.
I think, the best way to accomplish autofill for datetime
is to make like that:
* @ORM\Column(type="datetime", options={"default"="CURRENT_TIMESTAMP"})
Putting logic to constructor isn't right solution, because setting default values are SQL client responsibility. If you decide no longer use ORM - you will lost business logic. Plus, if using constructor you won't be able to add default timestamps to datetime
attributes for existing rows.