Search code examples
javascriptjqueryformssymfonysonata-admin

show hidden select type with javascript


I work with symfony framework and I have two select Type:

the 2nd select is initially Hidden and relative to the value of the first select the 2nd select will be displayed : for that I tried to do $this :

Script

<script type="text/javascript">
$(document).ready(function () {
    $('.type-produit ').change(function() {
     if ($('select[id$="_type"]>option:selected').text() == "Unité")
     {  $('.hidden ').show();  } 
    });
}); 
</script>

FormType

$formMapper
->add('type','choice', array(
     'choices' => array('Kg' => 'Kg', 'Unité' => 'Unité'),
     'label' => 'Type de vente',
     'attr' =>array('class'=>'type-produit')
))

->add('soustype',HiddenType::class, array(
     'data' => ['Liquide'=>'Liquide','Autres'=>'Autres'],
     'label' => 'Sous types',
     'attr'=>array('class'=>'hidden')
))

But the 2nd select still not displayed , someone can help me please ? thanks for all


Solution

  • Change the soustype field to choice type (HiddenType field is rendered as <input type="hidden">), then you can hide or show the field in the script.

    FormType

    ...
    ->add('soustype', 'choice', array(
            'choices' => ['Liquide'=>'Liquide','Autres'=>'Autres'],
            'label' => 'Sous types',
            'attr' => array('class'=>'soustype')
    ))
    

    Script

    $(document).ready(function () {
        $('.soustype').hide();
    
        $('.type-produit ').change(function() {
             if ($('select[id$="_type"]>option:selected').text() == "Unité") { 
                $('.soustype ').show();  
            }
        });
    });