Closed
Description
It appears constraints registered directly on a particular form field or model property are not getting called during a field's POST_SUBMIT event. I'm guessing the validation triggers only on the top most form POST_SUBMIT. This makes it difficult to add a dynamic field that relies on the validity of the field's submitted data.
$builder->add(
$builder->create('example', TextType::CLASS, array(
'constraints' => new Assert\NotBlank
)->addEventListener(FormEvents::POST_SUBMIT,
function (FormEvent $event) {
// always true unless a TransformationFailedException is thrown regardless of constraints attached
dump($event->getForm()->isValid())
})
);
Tested Symfony version 2.8.x
related #15342
related #13318
Edit:
A workaround is to use a model transformer. But displaying exceptions as validation error in view is tricky. Key is to pass field's Form::getTransformationFailure
value to the template.
Edit 2:
Another workaround
use Symfony\Component\Form\Form;
$isValid = function(Form $form) {
// Logic taken from Symfony\Component\Form\Extension\Validator\ValidatorExtension
$validator = \Symfony\Component\Validator\Validation::createValidator();
$metadata = $validator->getMetadataFor(Form::CLASS);
$metadata->addConstraint(new \Symfony\Component\Form\Extension\Validator\Constraints\Form());
$metadata->addPropertyConstraint('children', new \Symfony\Component\Validator\Constraints\Valid());
return !$validator->validate($form)->count();
};
$builder->add(
$builder->create('example', TextType::CLASS, array(
'constraints' => new Assert\NotBlank
)->addEventListener(FormEvents::POST_SUBMIT,
function (FormEvent $event) use($isValid) {
// always true unless a TransformationFailedException is thrown regardless of constraints attached
dump($event->getForm()->isValid());
// covers constraints only
$isValid($event->getForm());
})
);