Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2: Call to a member function format() on a non-object ... in DateTimeType.php

I have a DateTime field:

/**
 * Date time posted
 * @Column(type="datetime")
 */
private $dtPosted;

which is set to a default value by using a LifeCycleCallback

/**
 * @PrePersist
 */
function onPrePersist() {
    // set default date
    $this->dtPosted = date('Y-m-d H:m:s');

I am getting the following error:

Fatal error: Call to a member function format() on a non-object in D:\ResourceLibrary\Frameworks\Doctrine\lib\Doctrine\DBAL\Types\DateTimeType.php on line 46

like image 926
Jiew Meng Avatar asked Jul 31 '10 15:07

Jiew Meng


4 Answers

The date() function returns a string. The datetime type works with DateTime objects. So either change the mapping type to string or use DateTime objects.

like image 177
romanb Avatar answered Nov 18 '22 22:11

romanb


you could always use:

$this->updated = new \DateTime("now");

http://www.doctrine-project.org/docs/orm/2.0/en/cookbook/working-with-datetime.html

like image 28
space_balls Avatar answered Nov 18 '22 23:11

space_balls


Try and use your setCreated with annotations for @ORM\PrePersist and setUpdated with annotations for @ORM\PrePersist and @ORM\PreUpdate methods as opposed to prePersist and preUpdate methods...

/**
 * @ORM\PrePersist
 */
public function setCreated()
{
    $this->created = new \DateTime();
}

/**
 * @ORM\PrePersist
 * @ORM\PreUpdate
 */
public function setUpdated()
{
    $this->updated = new \DateTime();
}
like image 5
MediaVince Avatar answered Nov 18 '22 23:11

MediaVince


I came across a similar problem, but with a time field, and this question and @romanb 's answer helped.

I was getting the following error, much like the one in the question.

Call to a member function format() on a non-object in 
... /vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/TimeType.php on line 50

The solution was similar, for fields of the time datatype, Doctrine will accept an instance of PHP's DateInterval

$quizFixture1->setCompletionTime(\DateInterval::createFromDateString('743 seconds'));
like image 3
Adam Elsodaney Avatar answered Nov 18 '22 23:11

Adam Elsodaney