Search code examples
formssymfonysymfony-2.3formbuilder

How to auto-fill form with URL params in Symfony2


I have a view in Symfony 2.3 that shows a full list of employee likes and dislikes. I am trying to create a simple form at the top of this view to filter the list by employee by name.

I have currently created the form within a twig template using regular HTML and some TWIG conditional statements to check if the employee_name GET param matches one of the employees. This solution works but isn't ideal.

<form action="{{ path('report') }}" method="GET">
    <select id='employee_name' name='employee_name'>
         <option value='John' {% if app.request.get("employee_name") == 'John' %} selected {% endif %}>John</option>
         <option value='Aaron' {% if app.request.get("employee_name") == 'Aaron' %} selected {% endif %}>Aaron</option>
         <option value='Sam' {% if app.request.get("employee_name") == 'Sam' %} selected {% endif %}>Sam</option>
    </select>
    <button type="submit">Submit</button>
</form>

My question is, is there a way to write the above form using the Form Builder and still have it auto-fill the fields when submitting? I'd like my filter form to be scalable and reusable. Perhaps it be would better to just use an Twig Include? Suggestions welcome.


Solution

  • Sure. Just create the form with the form builder and render it in Twig. Since you're using the GET method and if you're calling $form->handleRequest($request), the form will have the right values selected based on GET parameters.