1

I'm new to Symfony and doctrine as well but I'm doing things based on the Documentation.

The error I get is: Error: Call to a member function format() on string and the code it gives for is in

vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\DateType.php at line 53   -
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
    return ($value !== null)
        ? $value->format($platform->getDateFormatString()) : null;
}
/**

The problem is that it tries to format the value of the Date type field. Here's my entity code generated with doctrine:

     /**
     * @var \DateTime
     */
    private $availableDate = '0000-00-00';

If I remove the default value of the Date field then it does not throw me this exception, but the problem is that this field can not contain null value in the database (MySQL), so if remove the default value and leave it blank it's going to try to insert null into it and I get error from MySQL.

I don't have a constructor, I use doctrine to insert new like thisL

              $product = new PsProduct2();
              $em = $this->getDoctrine()->getManager();

              $em->persist($product);
              $em->flush();

How can this be fixed?

Ervin
  • 2,374
  • 4
  • 30
  • 44
  • `'0000-00-00'` is a string, not a `\DateTime` object. – eggyal Jan 14 '16 at 13:09
  • I know that. But that's how Doctrine generates the entity file. If I change it to private $availableDate = new \DateTime('0000-00-00') I'm getting an error – Ervin Jan 14 '16 at 13:10
  • One presumes the error you're getting relates to the fact that the initialization is to a non-constant value? You could instead assign such a default value to `$availableDate` in the constructor. – eggyal Jan 14 '16 at 13:14
  • just updated the thread, I forgot to say I have no constructor – Ervin Jan 14 '16 at 13:32
  • 1
    You do have a constructor, even if it's only an implicit one. You're calling it when you do `new PsProduct2()`. Just define a function named `__construct()` in the `PsProduct2` class, within which you do `$this->availableDate = new \DateTime();`. – eggyal Jan 14 '16 at 13:36
  • I'm going to check that, thanks! Meanwhile I have found another solution which works fine, I have changed the mapping for this field from date to string, just like described in this thread: http://stackoverflow.com/questions/10897380/issue-handling-dates-in-doctrine-php – Ervin Jan 14 '16 at 13:39
  • Thanks eggyal, its working! Would you please write it in an answer? I think this would be a helpful answer for many out there. – Ervin Jan 14 '16 at 17:23

0 Answers0