S
S
sergmit2019-06-14 12:06:29
symfony
sergmit, 2019-06-14 12:06:29

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;

after creating a migration, a default value appears in the table (current_timestamp() ), if inserted directly into the database, the value is inserted,
if inserted through an entity, it gives an error - the field cannot be null, in theory this field should not be in the request at all ( it is there)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
Flying, 2019-06-14
@sergmit

Just initialize this field in the constructor or in the @PrePersistlifecycle event handler.

D
Dmitry Sviridov, 2019-06-14
@dimuska139

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

Then you need to connect this type to the Doctrine:
if (!Type::hasType(DefaultNow::DEFAULTNOW)) {
     Type::addType(DefaultNow::DEFAULTNOW, DefaultNow::class);
}

Well, in the column annotations in the entity, specify:
/**
     * @var \DateTime|null
     *
     * @ORM\Column(name="created_at", type="defaultnow")
     */
    private $createdAt;

D
DeadAndFat, 2019-06-18
@DeadAndFat

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 question

Ask a Question

731 491 924 answers to any question