【问题标题】:Symfony Validation of DateTime fails due to not being string?由于不是字符串,Symfony 验证 DateTime 失败?
【发布时间】:2020-07-15 12:55:42
【问题描述】:

我有以下内容:

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

注意:如果我使用'startDate' => '2020-01-01',那么它可以工作。 在 FormType 我有以下内容:

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

配置选项如下:

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

在事件实体中,我有一个这样的字段:

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

但我不断收到此错误,不知道为什么?

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

我有 Symfony 4.4.10。

【问题讨论】:

    标签: symfony symfony4 symfony-validator


    【解决方案1】:

    如果您尝试预设数据,submit 是不适合这项工作的工具。它的字面意思是处理标准化形式的提交(具有标量值和数组的数组)。而是使用FormFactory::create的第二个参数来预设数据:

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

    【讨论】:

    • 在 FormFactory 中? formFactory中没有createForm
    • 哦,你说得对,我指的是ControllerTrait。它只是create 的第二个参数。我的坏;o)
    • 然后我删除了 submit() 权利,现在我有了这个; Cannot check if an unsubmitted form is valid. Call Form::isSubmitted() before Form::isValid() 因为我想检查值是否正确
    • 我真的很困惑你的用例是什么,当你使用没有提交的表单时......你能在你的问题中澄清一下吗?如果没有提交,你为什么要验证?在这种情况下,顺便说一句。 ValidatorInterface 更适合直接验证...? $errors = $validator->validate($event);
    • 您是从 html 表单还是通过 api 接收数据?在这两种情况下,方法略有不同。 html 表单:symfony.com/doc/current/forms.html#processing-forms 和类似于 symfony.com/doc/current/form/direct_submit.html 的东西用于 api 提交。表单组件很智能,您不必为它“准备”数据,只需将一个包含标量/原始数据的数组传递给它。
    猜你喜欢
    • 2019-03-03
    • 2018-01-31
    • 2021-06-19
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    相关资源
    最近更新 更多