Search code examples
formssymfonydependenciesshow-hide

Symfony: Hide/Show form element dependent on dropdown selection with database entries


I hope my title is proper: I have a dropdown, that comes from a form as an EntityType and the values are from an entity class. Code:

   ->add('type', EntityType::class, array(
      'class' => 'DocumentBundle:DocumentType',
      'label' => 'label.type',
      'property' => 'translationKey',
      'required' => true,
      'multiple' => false,
      'expanded' => false,
      'empty_value' => 'label.select_type',
      'choice_translation_domain' => 'Documents'
      ))
  ->add('vka_number', 'text', array(
      'label' => 'label.vka_number',
      'required' => false,
      'translation_domain' => 'Documents'))

the second one is a text field (vka_number) that I only want to be shown when a specific value from that dropdown is selected in my twig template I render the elements:

<div class="row">
  <div class="col-md-6" id="documentDropdown">
    {{ form_row(form.type) }}
  </div>

  <div class="col-md-6" id="vka">
    {{ form_row(form.vka_number) }}
  </div>
</div>

I was thinking about a javascript function like that:

<script>
    $(document).ready(function(){
    $('#documentDropdown').on('change', function(){
       if (this.value == 'Contract')
       {
         $('#vka').show();
       }
        else {
         $('#vka').hide();
       }
    });
    });
    </script>

but it's not working and I think this is because it can't access the values from the dropdown since they are not hard coded but database entries. 'Contract' would be the entry (id=1) that "makes" the vka_number text field appear.


Solution

  • Here's my javascript function that eventually solved my problem.

     $(document).ready(function () {
        $('#type ').change(function() {
             if ($('select[id$="_type"]>option:selected').text() == "Contract") {
                $('#vka_number ').show();
            }
            else {
              $('#vka_number').hide();
            }
        });
    });