Search code examples
phpformsselecttwigdropdown

How to capture a selected option in twig and reselect it on an error resubmit?


I have a twig form where a select dropdown is populated with a variable from PHP. If the form throws an error, I need to capture the selected option and have it reselected again automatically. I can do this successfully with a normal input box through a PHP function like this:

   <label for="fname">First Name *</label>
   <input type="text" name="fname" id="fname" value="{{ populate.fname }}" required>
   {% if error.fname %}
       <label id="fname-data-error" class="error" for="fname">There is an error.</label>
   {% endif %}

How do I reselect the already captured selected data while keeping the other options available? I tried...

{% if error.car_models == true %} 
 <option value="{{ populate.car_models }}" selected>{{car_model.name}}</option>
{% else %}
 <option value="{{car_model.name}}">{{car_model.name}}</option>
{% endif %}

but that does not work. Here is my current twig code:

<label for="car_models">Car Models</label> 
<select name="car_models" id="car_models">
    {% for car_model in car_models.car_models %}
       <option value="{{car_model.name}}">{{car_model.name}}</option>
    {% endfor %}
</select>
{% if error.car_models %}
    <label id="car-model-error" class="error" for="car_models">There is an error.</label>
{% endif %}


Solution

  • I'm assuming error.car_models is a boolean and populate.car_models is a string.

    {% for car_model in car_models.car_models %}
      {% with %}
        {% set selected = error.car_models and populate.car_models is same as(car_model.name) %}
        <option value="{{car_model.name}}"{% if selected %} selected{% endif %}>{{car_model.name}}</option>
      {% endwith %}
    {% endfor %}