-1

I have this form type

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('field1', TextType::class)
        ->add('field2', TextType::class, [
            'required' => true
        ])
    ;
}

I would like to change the field2 required attribute to false, depending on field1. What I am trying to do:

$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
            $data = $event->getData();
            $form = $event->getForm();

            if(array_key_exists('field1', $data) && $data['field1'] === 'some value') {

                //here I need something to set field2 required option to false

            }
          
        });

in this way if I type "some value" in field1 and I submit the form, field2 is no longer mandatory.

Is it possible to achieve that?

Also, is it PRE_SUMBIT the correct event to use for this purpose?

Rufinus
  • 29,200
  • 6
  • 68
  • 84
user3174311
  • 1,714
  • 5
  • 28
  • 66
  • You could also try with a custom constraint using the [Callback constraint](https://symfony.com/doc/current/reference/constraints/Callback.html). [Like this here](https://stackoverflow.com/questions/42935452/unable-to-use-callback-assert-with-a-form-without-data-class). – Bossman May 24 '22 at 10:21
  • Did you try POST_SUBMIT as mentioned here https://symfony.com/doc/current/form/dynamic_form_modification.html? – qdequippe May 24 '22 at 13:31
  • The point is not really WHERE to do it but WHAT do to to change required from true to false and pass form validation. I think PRE_SUBMIT is the correct place as there I can manage data before to go to the validation. there, if I set a value for field2 it works, but this is not really what I want to do. – user3174311 May 24 '22 at 13:37

1 Answers1

-1

The required is only a html attribute (and depending on your view will invoke clientside validation, or change rendering).

If you depend on this then it would be better to validate the entity itself. For this you can use the Callback Assert. see https://symfony.com/doc/current/reference/constraints/Callback.html#the-callback-method for details.

Rufinus
  • 29,200
  • 6
  • 68
  • 84