I have the entity class in symfony like this
/**
* @var datetime $createDate
* @ORM\Column(name="create_date", type="datetime", nullable=false)
*
*/
private $createDate;
/**
* @return datetime
*/
public function getCreateDate(){
return $this->createDate;
}
public function setCreateDate(\DateTime $createDate){
$this->createDate=new \DateTime('today');
return $this;
}
basically i want to set the date to today while saving.
I am using JSON which gets are serilaized object and then i am deserializing it.
but this date object is not in that serilaizer and i want to set it when i persist the entity
This is simple case but i want to do some calculation on date and then save it.
There are different approaches. The simplest one is to set the createDate in the constructor:
public function __construct()
{
$this->createDate = new \DateTime();
}
The second one is - like Alexander already described - using a lifecycle callback method:
/**
* @ORM\Entity()
* @ORM\HasLifecycleCallbacks()
*/
class yourEntityClass
{
// ...
/**
* @ORM\PrePersist
*/
public function prePersist()
{
$this->createDate = new \DateTime();
}
}
The third one is using the Doctrine Extensions bundle, which comes with an annotation for that:
/**
* @var datetime $createDate
* @ORM\Column(name="create_date", type="datetime", nullable=false)
* @Gedmo\Timestampable(on="create")
*/
private $createDate;
This makes especially sense, if you also want to use additional behaviours that come with this bundle, for example the sluggable behaviour or the translatable behaviour.
/**
* @PrePersist
*/
function onPrePersist() {
// set default date
$this->createDate= date('today');
}
There might be e problem when updating entities but you can add a simple check to see if date has already been set.