Skip to content

Commit

Permalink
switch the context when validating nested forms
Browse files Browse the repository at this point in the history
  • Loading branch information
xabbuh committed Jun 11, 2020
1 parent f87c993 commit 96f56f5
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
Expand Up @@ -90,6 +90,7 @@ public function validate($form, Constraint $formConstraint)
// in different steps without breaking early enough
$this->resolvedGroups[$field] = (array) $group;
$fieldFormConstraint = new Form();
$this->context->setNode($this->context->getValue(), $field, $this->context->getMetadata(), $this->context->getPropertyPath());
$validator->atPath(sprintf('children[%s]', $field->getName()))->validate($field, $fieldFormConstraint);
}
}
Expand Down Expand Up @@ -129,6 +130,7 @@ public function validate($form, Constraint $formConstraint)
if ($field->isSubmitted()) {
$this->resolvedGroups[$field] = $groups;
$fieldFormConstraint = new Form();
$this->context->setNode($this->context->getValue(), $field, $this->context->getMetadata(), $this->context->getPropertyPath());
$validator->atPath(sprintf('children[%s]', $field->getName()))->validate($field, $fieldFormConstraint);
}
}
Expand Down
Expand Up @@ -21,6 +21,7 @@
use Symfony\Component\Form\Test\ForwardCompatTestTrait;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\Expression;
use Symfony\Component\Validator\Constraints\GroupSequence;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
Expand Down Expand Up @@ -283,6 +284,51 @@ public function testCascadeValidationToChildFormsUsingPropertyPathsValidatedInSe
$this->assertSame('This value should not be blank.', $violations[0]->getMessage());
$this->assertSame('children[field1].data', $violations[0]->getPropertyPath());
}

public function testContextIsPopulatedWithFormBeingValidated()
{
$form = $this->formFactory->create(FormType::class)
->add('field1', null, [
'constraints' => [new Expression([
'expression' => '!this.getParent().get("field2").getData()',
])],
])
->add('field2')
;

$form->submit([
'field1' => '',
'field2' => '',
]);

$violations = $this->validator->validate($form);

$this->assertCount(0, $violations);
}

public function testContextIsPopulatedWithFormBeingValidatedUsingGroupSequence()
{
$form = $this->formFactory->create(FormType::class, null, [
'validation_groups' => new GroupSequence(['group1']),
])
->add('field1', null, [
'constraints' => [new Expression([
'expression' => '!this.getParent().get("field2").getData()',
'groups' => ['group1'],
])],
])
->add('field2')
;

$form->submit([
'field1' => '',
'field2' => '',
]);

$violations = $this->validator->validate($form);

$this->assertCount(0, $violations);
}
}

class Foo
Expand Down

0 comments on commit 96f56f5

Please sign in to comment.