Object of class DateTime could not be converted to string - Symfony/PHP

Viewed 11305

When i submit my form it shows me this error:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class DateTime could not be converted to string").

Full message Error

I don't know what i'm doing wrong , this is my code ( PHP )

   ->add('purchasedate', DateType::class, array(
            'widget' => 'single_text',
            'html5' => false,
            'label' => 'Date d’achat (JJ/MM/AAAA)*',
          ))

Purchase Date:

/**
 * @var string
 *
 * @ORM\Column(name="purchasedate", type="date")
 * @Assert\Range(
 *      min = "2019-01-14",
 *      max = "2019-04-14"
 * )
 * 
 * 
 * @Serializer\SerializedName("purchasedate")
 * @Serializer\Expose()
 * 
 */

private $purchasedate;

Get and Set Method

Solution

I was trying to display the date in a twig template is where the error showed up. I only update the display code

{{ user.purchasedate|date('d-m-Y') }}
2 Answers

just add twig filter to your date

{{ mydate |date('d-m-Y') }}
->add('purchasedate', DateType::class, array(
    'widget' => 'single_text',
    'html5' => false,
    'label' => 'Date d’achat (JJ/MM/AAAA)*',
    'format' => 'yyyy-MM-dd',
));

if not

$date = DateTime::createFromFormat(format, db_date);

$date = $date->format('d/m/Y');

Related