【问题标题】:Symfony: Custom subform validationSymfony:自定义子表单验证
【发布时间】:2016-04-18 19:00:24
【问题描述】:

我的表单女巫使用自定义非映射子表单。

public function buildForm(FormBuilderInterface $builder, array $options) {

        $builder->add('subtype', 'my-subtype');
    }
}

子表单由多个字段组成,我需要同时对它们进行额外检查。回调约束非常适合这项工作。但是我找不到如何在整个子窗体上添加此约束的方法。

到目前为止,我已尝试在 setDefaultOptions() 中设置回调或在 buildForm() 中使用 setAttribute() 进行设置,但未评估回调。

目前我只是将回调添加到其中一个字段:

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('field1', 'text')
        ->add(
            'field2', 'text',
             array(
            'constraints' => array(
                new Callback(array(
                   'methods' => array(array($this, 'validateMyType'))
                ))
        )
    ));
}

public function validateMyType($data, ExecutionContextInterface $context) {
    // Validation failed...
    $context->addViolationAt('subtype', "mySubtypeViolation");
    return;
}

然而,这阻止了我在整个子类型上添加违规。无论我在 addViolationAt() 中使用什么,都会将违规添加到承载回调约束的字段中。

【问题讨论】:

    标签: php forms validation symfony constraints


    【解决方案1】:

    我很惊讶你不能在 setDefaultOptions() 中添加回调,因为我刚刚测试了这个并且它有效。我一开始肯定会这样做。

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'constraints' => new Callback([$this, 'test'])
        ]);
    }
    
    public function test($data, ExecutionContextInterface $context)
    {
        return;
    }
    

    并且test 方法被执行(我使用调试器检查)。

    【讨论】:

    • 好的。这是我的坏事。我有错误的默认声明(“'constraints', array(...”)。我仍然需要弄清楚如何将违规添加到其字段并作为整个子窗体。跨度>
    • 您需要使用您的违规的属性路径。 $context->buildViolation(...)->atPath('subtype') 应该可以解决问题。
    【解决方案2】:

    首先我在配置中有错字,所以没有触发回调方法。其次,error-bubbling 是自动设置的,因此错误被添加到整个表单中。所以我只需要手动禁用它。

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults([
            'error_bubbling' => false, // Automatically set to true for compound forms.
            'constraints' =>
            array(
                new Callback(array(
                    'methods' => array(array($this, 'validateMyType'))
                    ))
        )]);
    }
    

    比添加任何其他回调的违规行为:

    public function validateFacrMembership($data, ExecutionContextInterface $context) {
        $context->addViolation("invalidValueMessage");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多