2
votes

I'm facing an issue dealing with a NotNull constraint in a Symfony form validation.

Using the following form :

class SchedulableType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($options) {
            $form = $event->getForm();
                $form
                    ->add('dateFrom', DateTimeType::class, array(
                        'constraints' => array(
                            new NotNull()
                        ),
                        'widget' => 'single_text', // In order to manage format
                        'format' => 'y-MM-dd HH:mm:ss'
                    ))
                    ->add('dateTo', DateTimeType::class, array(
                        'constraints' => array(
                            new NotNull()
                        ),
                        'widget' => 'single_text', // In order to manage format
                        'format' => 'y-MM-dd HH:mm:ss'
                    ))
                    ->add('value', $options['valueType'], $options['valueOptions']);
        });
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'valueType' => null,
            'valueOptions' => array(),
        ));
    }
}

The data in my event are the following :

array (size=3)
  'dateFrom' => boolean false
  'dateTo' => boolean false
  'value' => string 'value' (length=5)

But I'm getting the following error message :

{
    "status": "400",
    "title": "This value should not be null.",
    "source": {
        "source": {
            "pointer": "/SCHEDULABLE/dateFrom/0"
        }
    }
},
{
    "status": "400",
    "title": "This value should not be null.",
    "source": {
        "source": {
            "pointer": "/SCHEDULABLE/dateTo/0"
        }
    }
}

Why a NotNull constraint throws an error if my value is false ?

You can have a look at the constraint class : symfony/src/Symfony/Component/Validator/Constraints/NotNullValidator.php

PS : The form validation is used in an API, it's why the error is JSON formatted.

1

1 Answers

3
votes

That's basically because those fields are DateTimeType so it tries to cast value to a valid \DateTime and since it won't happen anyway, it store a null value. Remember that the cycle is

  1. Data handling
  2. Object (or form) population via setter/adder/public properties
  3. Validation (in fact you're the responsible for this via isValid())

If you would like to accept false and implement some kind of logic like "set today date", you need to do yourself (maybe with FormEvents?)