Search code examples
symfonyvalidationdateconstraintsfosrestbundle

Symfony 3 Constraint validation Date or Datetime


I try to validate a date (or a datetime) with the validation of a form into Symfony (3.2).

I'm using FOSRestBundle to use the json from request (because i try to develop my personnal API)

But i've try a lot of format:

  • 2017-04-09
  • 17-04-09
  • for datetime:
    • 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 get always this error: This value is not valid

The function of my controller

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 entity

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
        ]);
    }
}

An example of request (i'm using Postman)

  • Method: POST
  • Header: application/json
  • Body (raw):

    {"place":{"name":"name","address":"an address","created":"1997-12-12"}}
    

I'm not sure that i use the right format, or if i missing anything in my files :/

Could you please switch on the light in my mind!?! :)

Thanks so much for your help. Fabrice


Solution

  • The problem at created field in your form type. When you add created field using $builder->add('created'); syntax, the default type Symfony\Component\Form\Extension\Core\Type\TextType will be applied and 1997-12-12 input data is a string, not a DateTime instance.

    To fix this issue, you should pass DateType in second argument: $builder->add('created', 'Symfony\Component\Form\Extension\Core\Type\DateType');. This form type has a transformer which will transform the input data 1997-12-12 into a DateTime instance.

    For more informations about Symfony's form types, have a look at Form Types Reference