Answer the question
In order to leave comments, you need to log in
Doctrine how to set default date value?
There is a model in which the field is specified:
/**
* @ORM\Column(type="datetime", options={"default": "CURRENT_TIMESTAMP"})
*/
private $created_at;
Answer the question
In order to leave comments, you need to log in
Just initialize this field in the constructor or in the @PrePersist
lifecycle event handler.
You need to create a custom type like this:
<?php
namespace MyProject\Types;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
class DefaultNow extends Type
{
const DEFAULTNOW = 'defaultnow'; // modify to match your type name
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
// return the SQL used to create your column type. To create a portable column type, use the $platform.
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
$dt = new \DateTime($value);
$dt->setTimezone(new \DateTimeZone('UTC'));
return $dt->format('Y-m-d H:i:s');
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if ($value == null)
return 'now()';
return $value;
// This is executed when the value is written to the database. Make your conversions here, optionally using the $platform.
}
public function getName()
{
return self::DEFAULTNOW; // modify to match your constant name
}
}
if (!Type::hasType(DefaultNow::DEFAULTNOW)) {
Type::addType(DefaultNow::DEFAULTNOW, DefaultNow::class);
}
/**
* @var \DateTime|null
*
* @ORM\Column(name="created_at", type="defaultnow")
*/
private $createdAt;
For fields createdAt, updateAt in the doctrine there is a trait: Timestampable
Accordingly, in the annotation of the class, you need to add@ORM\HasLifecycleCallbacks
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question