Symfony ChoiceType to enable or disable TextType

Viewed 230

I have a form in my Symfony 4 app. I have 2 fields, a ChoiceType and a TextType. Is it possible to enable the TextType if 'other' option is selected in the ChoiceType and disable if something else is selected?

This is my form currently:

$builder
    ->add('colour', ChoiceType::class, [
        'choices' => [
            'Red' => 0,
            'Green' => 1,
            'Blue' => 2,
            'Other' => 3
        ],
        'mapped' => false,
        'label' => 'What is your preferred colour?',
        'required' => false
    ])
    ->add('colour_other', TextType::class, [
        'mapped' => false,
        'label' => 'Please specify:',
        'required' => false,
        'disabled' => true
    ])
;

I would like to achieve this with the Symfony form builder, or would I need to write some custom javascript?

1 Answers

In this case you need to do this with JavaScript. Create an on change listener for the colour select. If the option, which should disable your colour_other field, was choosen then disable the input type text field.

A possible code could look like this (not tested):

$('select[name="colour"]').on('change', function() {
   if ($(this).val() == 3)  {   // If option 'Other' was selected
       $('input[name="colour_other"]').prop('disabled', false);
   } else {
       $('input[name="colour_other"]').prop('disabled', true);   // Change back if user selected another option later
   }
});
Related