0

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 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

In FormFactory? there is no createForm in formFactory
oh, you're right, I was referring to ControllerTrait. it's just the second parameter to create. my bad ;o)
Then I remove the submit() right, and now I have this though; Cannot check if an unsubmitted form is valid. Call Form::isSubmitted() before Form::isValid() As i want to check if the values are correct
I'm really confused what your use case is, when you're using forms without a submission ... can you clarify in your question? And if there's no submission, why would you want to validate? In that case, btw. a ValidatorInterface would be better suited to directly validate... ? $errors = $validator->validate($event);
do you receive data from a html form or via an api? in both cases there are slightly different approaches. html form: symfony.com/doc/current/forms.html#processing-forms and something similar to symfony.com/doc/current/form/direct_submit.html for api submissions. the form component is smart and you shouldn't have to "prepare" data for it, just pass it an array with scalar/raw data.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.