Reputation: 3145
I'm trying to store a mysql datetime in a Symfony repo and am getting an error. Tried several suggestions from the web and here on stack but nothing makes this error go away. This is what I'm trying to do (code is abbreviated for clarity)
My entity field:
/**
* @var \DateTime
*
* @ORM\Column(name="created", type="datetime")
*/
private $created;
My repo code:
$reservedays = 84;
$now = new \DateTime('NOW');
$now->modify('+' . $reservedays .' days');
$payment = new AppBundle\Entity\Payment;
$payment->setCreated( $now->format('Y-m-d h:i:s') );
But I am consistently getting this error:
Error: Call to a member function format() on string
500 Internal Server Error - FatalErrorException
Stack Trace:
1. in vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateTimeType.php at line 53 -
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return ($value !== null)
? $value->format($platform->getDateTimeFormatString()) : null;
}
/**
As you can see I want to take the current date and add 84 days to it and then store it into a mysql datetime but no matter what I've tried this error keeps coming up. Anyone?
Upvotes: 4
Views: 4348
Reputation: 1345
You're trying to save a string
in a datetime
column. Stop calling format() // <- Returns a string
and it'll work.
Also, you can simplify everything by initializing $createdAt
in your Payment object's constructor method. A constructor is called whenever a new instance of that class is invoked. You can also pass variables into the constructor.
// AppBundle\Entity\Payment
//...
class Payment
{
//...
// Set a default value for the passed-in variable.
public function __construct($reserveDays = 0)
{
$this->createdAt = new \DateTime('+'.$reserveDays.' days');
}
}
// AppBundle\Controller\PaymentController.php
//...
$payment = new AppBundle\Entity\Payment(84);
Upvotes: 1
Reputation: 2258
It's not necessary to use 'NOW' when creating new DateTime object. You can simply use $now = new \DateTime()
for actual date/time.
To your case - it's completely o.k. to create DateTime object, modify it by adding XYdays, so:
$reservedays = 84;
$now = new \DateTime();
$now->modify('+' . $reservedays .' days');
But then you should to use DateTime object as a setCreated()
method param, because the $created
property has \DateTime type. The Doctrine layer in Symfony takes care of proper persisting data to the DB, so this should work fine:
$payment = new AppBundle\Entity\Payment;
$payment->setCreated($now);
Upvotes: 4