0

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.

jave.web
  • 13,880
  • 12
  • 91
  • 125
  • Correcty me if i'm wrong, but i think you cannot add a field to a form after the validation, it's too late in the process. I'm doing this form mutation trick using Form Events https://symfony.com/doc/current/form/events.html. I can post a reply with consistent exemple if needed. – Erwan Haquet Apr 07 '23 at 11:37
  • so the only way would be custom "validation" or rather condition in the `buildForm` amd put only the addViolation part in the validation callback? – jave.web Apr 13 '23 at 06:33
  • I'm not sure of the use case, do you need to attach the error to the `myTestedField` ? otherwise, you could add the checkbox dynamically using https://symfony.com/doc/current/form/dynamic_form_modification.html#form-events-submitted-data, and add a constraint on this field. – Erwan Haquet Apr 13 '23 at 08:28
  • @ErwanHaquet thanks, I don't think it would help this case in particular, it may "help" some other case - those docs show me yet again Symfony forms are very very poorly designed, one would expect these things to be more out of the box. But again, thank you very much :-) – jave.web Apr 13 '23 at 21:44

0 Answers0