Reputation: 35973
I need to send with Postmal or in Curl by the console a field DateTime for my REST Api. But When I send the value always returns to me a not valid form so it doesn't insert into my database. If I try to change the field from DateTime to String and make a request with a string it works fine so the problem is the value sended I think
This is my Entity Birthday
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Birthday
*
* @ORM\Table(name="birthday")
* @ORM\Entity(repositoryClass="AppBundle\Repository\BirthdayRepository")
*/
class Birthday
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var \DateTime
*
* @ORM\Column(name="birthday", type="datetime")
*/
private $birthday;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set birthday
*
* @param \DateTime $birthday
*
* @return Birthday
*/
public function setBirthday($birthday)
{
$this->birthday = $birthday;
return $this;
}
/**
* Get birthday
*
* @return \DateTime
*/
public function getBirthday()
{
return $this->birthday;
}
}
This is my rest api inside a controller:
/**
* @Rest\Post("/users_birthday")
*/
public function postBirthdayAction(Request $request)
{
$birthday = new Birthday();
$form = $this->createForm(BirthdayType::class, $birthday);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($birthday);
$em->flush();
return $birthday;
//return new JsonResponse( [$data, $status, $headers, $json])
}
throw new HttpException(400, "Invalid data");
}
I have tried this:
curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
"birthday" : "2010-10-10 10:30:11"
}
' "http://symfony-rest-api.app/users_birthday"
and this:
curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
"birthday" : "04/21/15 20:56:16"
}
' "http://symfony-rest-api.app/users_birthday"
and this:
curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
"birthday" : "Tue, 02 Apr 2013 10:29:13 GMT"
}
' "http://symfony-rest-api.app/users_birthday"
No one works.
Can someone help me? Thanks
Upvotes: 1
Views: 795
Reputation: 21630
A field of type DateTime can be rendered in different ways. Your BirthdayType Form's birthday field must be configured as single_text type.
use Symfony\Component\Form\Extension\Core\Type\DateType;
...
$builder->add('birthday', DateType::class, array(
// render as a single text box
'widget' => 'single_text',
));
Upvotes: 1
Reputation: 7764
Sorry, my last answer was incorrect.
Can you try this please:
curl -i -X POST http://symfony-rest-api.app/users_birthday -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{"birthday" : "2010-10-10 10:30:11"}'
Not sure if that will work.
Upvotes: 0