0

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));
}
rickroyce
  • 950
  • 11
  • 24
  • Is `ent->setEventDate($req->get('event_date'));` the line which causes the error? Remember we can't see your line numbers. Anyway, what part of the error are you confused about, specifically? It's telling you the function excepts a DateTime object as input, but you gave it a string instead. The date you get from the request will always be text, because you can't send objects in a HTTP request. You need to parse the date string into a DateTime object and then pass _that_ to the setEventDate function. See https://www.php.net/manual/en/datetime.createfromformat.php for details – ADyson May 05 '23 at 11:04
  • sorry for the line numbers but yes for now am just testing if this add function is correct i'll try and format the $req->get('event_date') into a date format for now thanks for the help – massaoud ghassen May 05 '23 at 11:09

1 Answers1

0

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!

rickroyce
  • 950
  • 11
  • 24