简体   繁体   中英

how to remove datetime error in symfony2?

i make an entity in symfony2 and i set the entity as createddatetime and updateddatetime,but when i used setter in controller the error occur like this

FatalErrorException: Error: Call to a member function format() on a non-object in C:\wamp\www\QuickBacklog\vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\DateTimeType.php line 44

and here is my code of entity:

/**
     * Set createdDatetime
     *
     * @param \DateTime $createdDatetime
     * @return Sections
     */
    public function setCreatedDatetime($createdDatetime)
    {
        $this->createdDatetime = $createdDatetime;

        return $this;
    }

    /**
     * Get createdDatetime
     *
     * @return \DateTime 
     */
    public function getCreatedDatetime()
    {
        return $this->createdDatetime;
    }

    /**
     * Set updatedDatetime
     *
     * @param \DateTime $updatedDatetime
     * @return Sections
     */
    public function setUpdatedDatetime($updatedDatetime)
    {
        $this->updatedDatetime = $updatedDatetime;

        return $this;
    }

    /**
     * Get updatedDatetime
     *
     * @return \DateTime 
     */
    public function getUpdatedDatetime()
    {
        return $this->updatedDatetime;
    }

but when i write in controller

$date=date('Y-m-d H:i:s');
$entity->setCreatedDatetime($date);
$entity->setUpdatedDatetime($date);

the error occurs how i remove this error?

updatedDatetime and createddatetime need to be objects of DateTime class.

so your controller code should be something like:

$date= new \DateTime();
$entity->setCreatedDatetime($date);
$entity->setUpdatedDatetime($date);

As the other post mentions, your entity expect the type to be DateTime , but I feel like an additional bit of information but help you out in the future.

With doctrine, you can add events (such as prePersist ), so you could add a function called setDefaultCreatedDatetime which would look like:

public function setDefaultCreatedDatetime()
{
    $this->setCreatedDatetime(new \DateTime());
}

you can then add:

lifecycleCallbacks:
    prePersist: [setDefaultCreatedDatetime]

to your doctrine entity. This will save you having to call this method manually.

You can also do the same for your setUpdatedTime and use the preUpdate event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM