【问题标题】:Symfony 2 form conditional required field with fields not mapped to entitySymfony 2 表单有条件的必填字段,字段未映射到实体
【发布时间】:2015-01-30 10:07:20
【问题描述】:

我有一个表单,只有在选择 requireField 时才需要字段 conditionalRequiredField

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add(
            'requireField', 'choice', array
            (
                'label' => ' ',
                'mapped' => false,
                'choices' => array
                (
                    'require' => 'Should I require that field?'
                ),
                'multiple' => true,
                'expanded' => true
            )
        )
        ->add(
            'conditionalRequiredField', 'text', array
            (
                'label' => 'I am required because the field above was selected',
                'class' => 'AppBundle\Entity\SomeEntity',
            )
        )

...以及其他一些字段,其中一些映射到实体。

第一个字段未映射到实体。所以在控制器中,当我访问$form->getData() 时它不可用,它只能通过 Request 对象使用。现在的问题是,我应该如何以及在哪里添加验证才能正确执行?仅使用isValid() 方法验证整个表单,而在其他地方没有任何额外的逻辑?我可能可以在某个地方进行验证,但感觉不对。我已经阅读了很多关于约束和验证器的内容,但它们似乎都与实体字段相关联。

感谢您的帮助:-)。

【问题讨论】:

    标签: forms validation symfony


    【解决方案1】:

    假设您链接到此 FormType 的实体调用 MyEntity

    你可能应该有这样的东西:

    /**
     * @My\CustomValidation
     */
    class MyEntity
    {
        private $requiredField;
    
        /**
         * @ORM\Column(type="string")
         */
        private $conditionalRequiredField;
    }
    

    为了创建您的自定义验证,您可以查看http://symfony.com/doc/current/cookbook/validation/custom_constraint.html#class-constraint-validator 创建类约束验证器

    您的验证方法将如下所示:

    public function validate($entity, Constraint $constraint)
    {
        if(!$entity instanceof MyEntity){
            return;
        }
    
        if($entity->getRequiredField() && $entity->getConditionalRequiredField() == null) {
            $this->context->addViolationAt('conditionalRequiredField', 'you.error.flag', array(), null);
        }
    }
    

    【讨论】:

    • 非常感谢! :-)。我的主要问题是我没有意识到您实际上可以在 Entity 中创建一个未映射到数据库字段的字段。当您向我展示了这一点时,我已经阅读了很多关于约束和验证器的内容,当我将表单中的值映射到实体属性时,我可以轻松地验证表单。基本上这解决了我的问题。
    • BTW PhpStorm “说” addViolationAt 已被弃用
    • 是的,我从一个 Sf2.4 项目中获取了这个 sn-p,如果你使用的是 Sf2.6,你可以查看stackoverflow.com/questions/25264922/…
    • 是的,这就是我在您在答案中提供的上一个链接中使用的,再次非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多