【问题标题】:Symfony2 - validating additional form elementsSymfony2 - 验证额外的表单元素
【发布时间】:2013-06-21 21:37:23
【问题描述】:

如何验证我的实体中不存在且甚至与它们无关的其他表单字段?

例如:用户需要接受规则,以便我可以添加一个额外的复选框,并将映射设置为 false,但是如何添加验证此字段的约束?

甚至更高级:用户需要在表单中正确地重复他的电子邮件和密码。如何验证它们是否相同?

我想避免在我的实体中添加这些字段,因为它们没有任何关系。

我使用 Symfony 2.3。

【问题讨论】:

    标签: symfony logic constraints


    【解决方案1】:

    一种方法是将约束直接挂在表单元素上。例如:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $notBlank = new NotBlank();
    
        $builder->add('personFirstName', 'text', array('label' => 'AYSO First Name', 'constraints' => $notBlank));
        $builder->add('personLastName',  'text', array('label' => 'AYSO Last Name',  'constraints' => $notBlank));
    

    对于重复的东西,查看重复的元素:http://symfony.com/doc/current/reference/forms/types/repeated.html

    另一种验证方法是为您的实体创建一个包装器对象。包装器对象将包含其他不相关的属性。然后,您可以在 validation.yml 中设置约束,而不是直接在表单上。

    最后,您可以为一个属性构建一个表单类型并为其添加约束:

    class EmailFormType extends AbstractType
    {
    public function getParent() { return 'text'; }
    public function getName()   { return 'cerad_person_email'; }
    
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'label'           => 'Email',
            'attr'            => array('size' => 30),
            'required'        => true,
            'constraints'     => array(
                new Email(array('message' => 'Invalid Email')), 
            )
        ));
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-27
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多