简体   繁体   English

如何在Symfony2中“动态”禁用一个变压器验证错误

[英]How to disable one transformer validation error “dynamically” in Symfony2

I have a form with many fields and validation groups, these fields contains some view data transformers too. 我有一个包含许多字段和验证组的表单,这些字段也包含一些视图数据转换器。

I need suppress the validation form partially ( Groups based on the Submitted Data ): 我需要部分取消验证表单( 基于提交数据的组 ):

use AppBundle\Entity\Client;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

// ...
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'validation_groups' => function (FormInterface $form) {
            $data = $form->getData();

            if (Client::TYPE_PERSON == $data->getType()) {
                return array('person');
            }

            return array('company');
        },
    ));
}

When you do that, the form will still run basic integrity checks ( Disabling Validation ) and validation errors coming from transformers they are thrown still ( Creating the Transformer ). 当您执行此操作时,表单仍将运行基本完整性检查( 禁用验证 ),而来自转换器的验证错误仍将被抛出( 创建转换器 )。

Use the POST_SUBMIT event and prevent the ValidationListener from being called ( Suppressing Form Validation ): 使用POST_SUBMIT事件并防止ValidationListener被调用( 禁止表单验证 ):

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
        $event->stopPropagation();
    }, 900); // Always set a higher priority than ValidationListener

    // ...
}

It is not a solution for me, since accidentally disable something more than just form validation. 对于我来说,这不是一个解决方案,因为意外禁用的功能不只是表单验证。

The question is: How to disable one transformer validation error "dynamically"? 问题是: 如何“动态”禁用一个变压器验证错误?

Example: 例:

I have a form field of RepeatedType belonging to person validation group and contains a view transformer ( RepeatedType ), this transformer throws an exception when the values in the array they are not the same ( ValueToDuplicatesTransformer ). 我的一个形式字段RepeatedType属于person验证组和包含视图变压器( RepeatedType ),该变压器抛出异常时,数组中的值它们是不相同的( ValueToDuplicatesTransformer )。

So, even when validation group is company , the form show errors belonging to RepeatedType field coming from transformer it. 因此,即使验证组是company ,该窗体也会显示来自Transformer的,属于RepeatedType字段的错误。

The question here is: How to disable the ValueToDuplicatesTransformer errors when validation group is not person ? 这里的问题是: 当验证组不是person时,如何禁用ValueToDuplicatesTransformer错误?

Because the buildForm misses the code related to adding the fields I assume: 因为buildForm错过了与添加字段有关的代码,所以我假设:

  1. you don't relate the form to an Entity via data_class directly, but set values in your controller 您不直接通过data_class将表单与实体相关联,而是在控制器中设置值
  2. the repeated type has required => true as an option and is there to validate a password repeated类型required => true作为选项,并且可以用来验证密码
  3. the $data that is passed to the formbuilder contains a value for the repeated field. 传递给formbuilder的$data包含repeated字段的值。

The problem basically is that validation is triggered. 基本上,问题在于验证已触发。 If there is any data, then the type will always do it's basic validations (the repeated field should have the same value twice). 如果有任何数据,则该类型将始终执行其基本验证(重复的字段应具有两次相同的值)。

What you should do to solve this is do not pass the value to $data in the first place, and make sure required => false for the repeated field. 解决此问题的方法首先是不要将值传递给$data ,并确保重复字段的required => false Your form will only do the group validation after that , as you already explained. 如前所述,您的表单将仅在此之后进行组验证。

Maybe the most robust solution is even different, and would it be best to make two FormTypes instead of using the groups . 也许最健壮的解决方案甚至有所不同,并且最好做成两个FormTypes而不是使用groups This will remove most of the complexity you describe in your question. 这将消除您在问题中描述的大多数复杂性。

You can't really deactivate errors from a DataTransformer, these errors are added by FormValidator and this behavior is not customizable. 您不能真正取消激活DataTransformer中的错误,这些错误是由FormValidator添加的,并且此行为不可自定义。 This is quite logical since transformation errors leads to the model data being in a broken state. 这是很合逻辑的,因为变换错误导致模型数据处于损坏状态。

What I would do in this case is use 2 field instead of a repeated field with the second one with mapped => false and an event listener that add the error manually when needed. 在这种情况下,我将使用2字段而不是重复的字段,而第二个字段使用mapped => false和事件侦听器,该侦听器在需要时手动添加错误。

Maybe I'm wrong, but the validation group is not a right tool to solve the problem at all. 也许我错了,但是验证小组根本不是解决问题的正确工具。 The dependency of validation rules you want to solve is based on data, while the validation group is not about it, it's about the same data being validating differently depending on context. 您要解决的验证规则的依存关系是基于数据的,而验证组与之无关,而是有关同一数据根据上下文进行不同验证的信息。

If you want to apply some rules only for person (or, the opposite, only for company), I would rather implement custom checking in Client Entity 如果您只想对某些人(或相反,仅对公司)应用某些规则,则我想在客户实体中实施自​​定义检查

namespace AppBundle\Entity;

class Client {
....
/**
* @Assert\IsTrue(message="Person should have a valid Title")
*/
public function isPersonTitleValid()
{
  return $this->type != Client::TYPE_PERSON || $this->isTitleValid();
}

public function isTitleValid()
{
  // Here implement your validation applicable only for person;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM