I'm using Doctrine 2 with ZF2 and the Doctrine-Module. I've written an Entity that needs a PreUpdate|PrePersist, because Doctrine doesn't allow Date|Datetime in a primary key:
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
*
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
* @ORM\Table(name="sample")
*/
class Sample
{
/**
*
* @ORM\Id
* @ORM\Column(type="string")
* @var integer
*/
protected $runmode;
/**
*
* @ORM\Id
* @ORM\Column(type="date")
* @var DateTime
*/
protected $date;
public function getRunmode()
{
return $this->runmode;
}
public function setRunmode($runmode)
{
$this->runmode = $runmode;
return $this;
}
public function getDate()
{
return $this->date;
}
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
*
* @ORM\PreUpdate
* @ORM\PrePersist
*/
protected function formatDate()
{
die('preUpdate, prePersist');
if ($this->date instanceof \DateTime) {
$this->date = $this->date->format('Y-m-d');
}
return $this;
}
}
The Problem is now, if i set a DateTime as a Date I get the message:
"Object of class DateTime could not be converted to string"
because it doesn't walk into the formatDate.
First of all, since you mapped the field
Sample#date
asdatetime
, it should always be eithernull
or an instance ofDateTime
.Therefore, you should typehint your
setDate
method as following:Also, your lifecycle callback is not invoked because the visibility of method
formatDate
isprotected
, therefore not accessible by the ORM. Change it intopublic
and it will work. No conversion should be necessary anyway, so you can get rid of it.