Following the Doctrine guidelines I understand how to set a default value for an Entity, but what if I wanted a date/time stamp?
My problem is my database has a default of NOW() on a field but when I use Doctrine to insert a record the values are null or blank but the rest of the insert happened.
Also since Doctrine says to declare the default as a const, this also creates a problem.
Suggestions?
Ok I found the solution:
The prePersist
option is what I'm doing.
Make sure you define in the annotations
<?php
/** @Entity
* @HasLifecycleCallbacks
*/
class User
and here is the function example they offer
/**
* @PrePersist
*/
public function doStuffOnPrePersist()
{
$this->createdAt = date('Y-m-d H:i:s');
}
And if you're using ORM like I am
<?php
/** @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class User
and here is the function example they offer
/**
* @ORM\PrePersist
*/
public function doStuffOnPrePersist()
{
$this->createdAt = date('Y-m-d H:i:s');
}
In my experience it is best to put everything in your Entities and not try to force your database to bypass the ORM.
<?php
namespace Phill\PaffordBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Stack
* @ORM\Table()
*/
class Stack
{
/**
* @var integer
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var \DateTime
* @ORM\Column(type="datetime")
*/
private $startDate;
public function __construct()
{
$this->startDate = new \DateTime();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With