symfonysymfony-formsdynamic-forms

SYMFONY - Display an input according to the value of a drop-down list


I'm learning how to use Symfony and I'm stuck on a form. I have a drop-down list, and depending on the choice, I would like to display an input. I have been looking for a solution for more than 4 days, but I can't find anything, so I come here to ask for your help

When I select "Lycéen.ne" in this dropdown list : dropdownList, I would like to display the input "Lycée" : inputLycee

I know there are FormEvent, but I don't really understand how it works and how to use JS to show or hide inputs

Thanks for your help =)


Solution

  • You can keep use Symfony to render the entire form and then use a bit of JS and CSS to hide or show the field that should be shown dynamically. Here's an example using plain JS:

    let foo = document.getElementById("foo");
    let bar = document.getElementById("bar");
    
    foo.addEventListener('change', (event) => {
        if (event.target.value === 'two') {
        bar.style.display = 'inline'; // Show the element.
      } else {
        bar.style.display = 'none'; // Hide the element.
      }
    });
    #bar {
      display: none; // Hide the element initially. 
    }
    <select name="foo" id="foo">
      <option value="one">Do not show</option>
      <option value="two">Show</option>
    </select>
    
    <input name="bar" id="bar" value="" placeholder="type something here..." >