I have a working Symfony 6 form with working validation defined aprox. like this:
$builder
->add('myTestedField', ChoiceType::class, [
'label' => 'My Field',
'attr' => [
//...
],
'choices' => [...],
'constraints' => [
new Assert\NotBlank(),
new Assert\Callback($this->validateMyField(...)),
],
Now the issue is that I want to alter the form IF and ONLY IF the validation in validateMyField()
fails, so I tried to store the $builder
in the buildForm()
in hopes that it could somehow be used later, I was wrong, following doesn't work:
private function validateMyField(?int $fieldInput, ExecutionContextInterface $context, $payload): void
{
$can = false;
if (...some validation condition...) {
$can = true;
}
if (!$can)
{
$this->builder->add('someCheckbox', CheckboxType::class, [
'label' => 'some checkbox label',
]);
$context->buildViolation('some error')
->atPath('myTestedField')
->addViolation()
;
}
}
The purpose is that I want to ask the user about forcing data override - if the validation fails for certain reasons - user can still force the update to happen - but they must be always warned beforehand and confirm that action.
I can't display the checkbox initially(on first form load) - would cause user issues later on.
I am also trying to avoid checking the information in the controller as I want to have the validation in the form class.