Symfony 2表单带有验证组,错误映射到错误的属性吗? [英] Symfony 2 forms with validation groups, errors mapped to the wrong property?

查看:96
本文介绍了Symfony 2表单带有验证组,错误映射到错误的属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前从来没有这个问题.

Never had this problem before.

  • 用电话填写表格,姓氏留空
  • 提交表单(验证组变为DefaultCreate)
  • 错误姓氏为必填项".映射到错误的$phone字段,而应映射到$lastName本身的属性
  • Fill the form with a phone, leaving lastname blank
  • Submit the form (and the validation groups become Default and Create)
  • The error "Last name is required." is mapped on the wrong $phone field, while should be mappend to $lastName itself property

您能重现同样的问题吗?

Can you reproduce the same issue?

$phone属性在Create验证组中,而$ phone在Default隐式组中:

$phone property is in the Create validation group, while $phone in Default implicit group:

class User
{
    /**
     * @Assert\NotBlank(groups={"Create"}, message="Last name is required.")
     *
     * @var string
     */
    protected $lastName;

    /**
     * @Assert\NotBlank(message="Phone is required.")
     *
     * @var string
     */
    protected $phone;
}

我根据提交的数据确定验证组:

I determine the validation groups based on submitted data:

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('lastName', 'text');
        $builder->add('phone', 'text');
        $builder->add('submit', 'submit');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'required' => false,
            'data_class' => 'Acme\HelloBundle\Entity\User',
            'validation_groups' => function (FormInterface $form) {    
                return null === $form->getData()->getId()
                    ? ['Default', 'Create']
                    : ['Default', 'Edit'];
            }
        ]);
    }
}

推荐答案

警告验证API 2.5存在错误

花了几个小时,但我发现了!其实是一个问题( https://github.com/symfony/symfony/issues/11003)用于新的验证器API 2.5.

Warning there is a bug with validation API 2.5

Took a couple of hours but I found it! Actually is an issue (https://github.com/symfony/symfony/issues/11003) for the new validator API 2.5.

临时解决方案(编译器阶段):

Temporary solution (compiler pass):

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Validator\Validation;

class SetValidatorBuilderApiVersionWorkaround implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
        // TODO remove when https://github.com/symfony/symfony/issues/11003
        // is fixed (validation errors added to the wrong field)
        $container->getDefinition('validator.builder')
            ->addMethodCall('setApiVersion', [Validation::API_VERSION_2_4]);
    }
}

这篇关于Symfony 2表单带有验证组,错误映射到错误的属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆