问题
Never had this problem before.
- Fill the form with a phone, leaving lastname blank
- Submit the form (and the validation groups become
Default
andCreate
) - 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