Skip to content

[Form] form config constraints overwrites extra_fields cause constraint #27362

Closed
@AlexeyDubinchak

Description

@AlexeyDubinchak

Symfony version(s) affected: >=3.4.5

Description
forms with disabled 'allow_extra_fields' and with defined constraints in options return wrong constraint in error cause

How to reproduce

 class NoExtraFieldsType extends AbstractType
 {
     ...
     public function configureOptions(OptionsResolver $resolver)
     {
         $resolver->setDefaults([
             'allow_extra_fields' => false,
             'csrf_protection' => false,
             'constraints' => [new SomeConstraint()]
         ]);
     }
 }
$form = $this->createForm(NoExtraFieldsType::class);
$form->submit([
    'existing_field' => 12345,
    'not_allowed_extra_field'
]);

foreach ($form->getErrors() as $error) {
    print_r([
        'message' => $error->getMessageTemplate(),
        'cause' => get_class($error->getCause()->getConstraint())
    ]);
}

<=3.4.4 (correct)

Array
(
[message] => This form should not contain extra fields.
[cause] => Symfony\Component\Form\Extension\Validator\Constraints\Form
)

>=3.4.5 (incorrect)

Array
(
[message] => This form should not contain extra fields.
[cause] => AppBundle\Validator\Constraints\SomeConstraint
)

Here is a repository with a reproduction of the problem : https://github.com/AlexeyDubinchak/symfony-formerror-issue

Possible Solution
Symfony\Component\Form\Extension\Validator\Constraints\FormValidator -> validate method

my guess problem is form validator runs this method in a loop for each constraint and is overwriting constraint property for cause

/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php#126
        // Mark the form with an error if it contains extra fields
        if (!$config->getOption('allow_extra_fields') && count($form->getExtraData()) > 0) {
            $this->context->setConstraint($constraint);

caused because of #25940

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions