0

working with doctrine and mongodb, I would like to set a datetime to a default value (new Datetime()) only when the record is create and only if no value is passed? Can I do this with annotations?

thanks

user3174311
  • 1,714
  • 5
  • 28
  • 66
  • Possible duplicate of [Default value in Doctrine](http://stackoverflow.com/questions/3376881/default-value-in-doctrine) – CountZero Jul 31 '16 at 20:48

1 Answers1

0

No, you would do this in the __construct() method of the mapped Entity class. This way every time you call new EntityClass() it will be set. Long before any doctrine persistence kicks in.

Just:

public function __construct() {
    $this->dateProperty = new \DateTime()
}
mblaettermann
  • 1,916
  • 2
  • 17
  • 23
  • thanks but I need to do this only when the record is created, not updated. I solved doing a find before the persist statement. – user3174311 Jul 31 '16 at 13:41
  • This it actually what it does. Doctrine does not call the Constructor when fetching entities from the database. – mblaettermann Jul 31 '16 at 13:46
  • *Doctrine does not call the Constructor when fetching entities from the database* Are you sure? I think that the constructor is called but the value of `dateProperty` will be overwritten by value fetched from the database. – A.L Jul 31 '16 at 19:24
  • @A.L Yeah pretty much. The properties are set by reflection when fetching via ObjectManager. – mblaettermann Jul 31 '16 at 19:52