Symfony 3 Confirmation Date or Date-Time
I'm trying to validate a date (or datetime) with form validation in Symfony (3.2).
I am using FOSRestBundle to consume json from request (because I am trying to develop my personal API)
But I tried a lot of format:
- 2017-04-09
- 17-04-09
- for date and time:
- 2017-04-09 21:12:12
- 2017-04-09T21: 12: 12
- 2017-04-09T21: 12: 12 + 01: 00
- ...
But the form is not valid and I always get this error: This value is not valid
My controller function
public function postPlacesAction(Request $request) {
$place = new Place();
$form = $this->createForm(PlaceType::class, $place);
$form->handleRequest($request);
if ($form->isValid()) {
return $this->handleView($this->view(null, Response::HTTP_CREATED));
} else {
return $this->handleView($this->view($form->getErrors(), Response::HTTP_BAD_REQUEST));
}
}
My essence
class Place
{
/**
* @var string
*
* @Assert\NotBlank(message = "The name should not be blank.")
*/
protected $name;
/**
* @var string
*
* @Assert\NotBlank(message = "The address should not be blank.")
*/
protected $address;
/**
* @var date
*
* @Assert\Date()
*/
protected $created;
// ....
// Getter and setter of all var
My entity type
class PlaceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
$builder->add('address');
$builder->add('created');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'MyBundle\Entity\Place',
'csrf_protection' => false
]);
}
}
Sample request (I am using Postman)
- Method: POST
- Header: application / json
-
Body (raw):
{"place":{"name":"name","address":"an address","created":"1997-12-12"}}
I'm not sure if I'm using the format I want, or if my files don't have anything: /
Could you turn on the lights in my mind!?! :)
Many thanks for your help. Fabrice
source to share
The problem is a field created
in your form type. When you add a field created
using syntax $builder->add('created');
, the default type is applied Symfony\Component\Form\Extension\Core\Type\TextType
and the input 1997-12-12
is a string, not an instance DateTime
.
To resolve this problem, you need to pass DateType
the second argument: $builder->add('created', 'Symfony\Component\Form\Extension\Core\Type\DateType');
. This type of form has a transformer that converts the input 1997-12-12
to an instance DateTime
.
For more information on Symfony Form Types see the Form Types Reference
source to share