代码之家  ›  专栏  ›  技术社区  ›  Nico

为什么symfony notnull containt为false抛出错误?

  •  1
  • Nico  · 技术社区  · 8 年前

    我面临着一个问题 NotNull symfony表单验证中的约束。

    使用以下表格:

    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(),
            ));
        }
    }
    

    我的事件中的数据如下:

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

    但我收到了以下错误消息:

    {
        "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"
            }
        }
    }
    

    为什么是 非零 如果我的值是 false ?

    您可以查看约束类: symfony/src/Symfony/Component/Validator/Constraints/NotNullValidator.php

    聚苯乙烯 :表单验证用于API,这就是错误是JSON格式的原因。

    1 回复  |  直到 8 年前
        1
  •  2
  •   DonCallisto    8 年前

    那基本上是因为那些领域 DateTimeType 所以它 tries to cast value to a valid \DateTime 既然它不会发生,它储存了 null 价值。 记住循环是

    1. 数据处理
    2. 通过setter/adder/public properties填充对象(或窗体)
    3. 验证(事实上你是通过 isValid() )

    如果你愿意接受 false 实现某种逻辑,比如“设置今天的日期”,你需要自己做(也许 FormEvents ?)