phpdatetimesymfony5

PHP Variable "must be of type DateTimeInterface, string given" error


am working with symfony and i have avariable of type DateTimeInterface and i want to pass it in the url request in postman but it keeps giving me this error :

Argument #1 ($eventDate) must be of type DateTimeInterface, string given, called in C:\xampp\htdocs\Pidev\PIDEVWeb\src\Controller\JEventController.php on line 39 (500 Internal Server Error)

#[Route('/addEvent',name:'add_event')]
public function add(Request $req,EventRepository $repo,EntityManagerInterface $em,NormalizerInterface $normalizer):Response
{
    $event=new Event();
    $event->setEventName($req->get('event_name'));
    $event->setEventDescription($req->get('event_description'));
    $event->setEventDate($req->get('event_date'));
    $event->setEventLocation($req->get('event_location'));
    $event->setEventStatus('ongoing');
    $em->persist($event);
    $em->flush();
    $jsonContent= $normalizer->normalize($event,'json');
    return new Response(json_encode($jsonContent));
}

Solution

  • Like the error message says, it want a dateTime object and not a string from a request.

    So you have to convert the date as string into an object, which implements the dateTimeInterface:

    $event->setEventDate(new DateTime($req->get('event_date')));
    

    Keep in mind, that you not validate the string, if it's really a DateTime parsable string. So if you input nonsense instead of a date, the DateTime object is not valid and you got an error again.

    Good luck!