Symfony Validation of DateTime fails due to not being string?

477 Views Asked by At

I have the following for:

formFactory->create(FormType::class);
$form->submit(['startDate' => new \DateTime('2020-01-01')]);

Note: if I use 'startDate' => '2020-01-01' then it works. Within FormType I have the following:

$builder->add('startDate', DateType::class, [
    'widget' => 'single_text',
    'format' => 'yyyy-MM-dd',
]);

The config options are as follows:

public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Event::class
        ]);
    }

And in the Event entity I have a field like this:

/**
     * @var \DateTime
     * @ODM\Field(type="date")
     * @Assert\NotBlank()
     */
    private $startDate;

Yet I keep getting this error and not sure why?

"startDate":["This value is not valid."]

I have Symfony 4.4.10.

1

There are 1 best solutions below

6
On

In case you're trying to pre-set data, submit is the wrong tool for the job. It's literally meant to handle a submission in normalized form (array with scalar values and arrays). Instead use the second parameter for FormFactory::create to preset data:

$event = new Event();
$event->setStartDate(new \DateTime('2020-01-01'));
$form = $formFactory->create(FormType::class, $event);