Symfony 2 forms with validation groups, errors mapped to the wrong property?

半世苍凉 提交于 2019-12-11 02:26:39

问题


Never had this problem before.

  • 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 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'];
            }
        ]);
    }
}

回答1:


Instead of using a compiler pass, you can edit config.yml to set the API to 2.4 :

validation:
    enable_annotations: true
    api: 2.4 # default is auto which sets API 2.5 BC

When the bug is resolved in 2.5, just remove the api setting and you will get back to 2.5 backward compatible.




回答2:


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]);
    }
}


来源:https://stackoverflow.com/questions/24150574/symfony-2-forms-with-validation-groups-errors-mapped-to-the-wrong-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!