如何在树枝中捕获选定的选项并在错误重新提交时重新选择它?
How to capture a selected option in twig and reselect it on an error resubmit?
我有一个树枝形式,其中 select 下拉列表填充了来自 PHP 的变量。如果表单抛出错误,我需要捕获 selected 选项并自动重新selected。我可以通过像这样的 PHP 函数使用普通输入框成功完成此操作:
<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 %}
如何在保持其他选项可用的同时重新select 已捕获的 selected 数据?我试过了...
{% 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 %}
但这不起作用。这是我当前的树枝代码:
<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 %}
我假设 error.car_models
是一个 布尔值 而 populate.car_models
是一个 字符串 .
{% 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 %}
我有一个树枝形式,其中 select 下拉列表填充了来自 PHP 的变量。如果表单抛出错误,我需要捕获 selected 选项并自动重新selected。我可以通过像这样的 PHP 函数使用普通输入框成功完成此操作:
<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 %}
如何在保持其他选项可用的同时重新select 已捕获的 selected 数据?我试过了...
{% 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 %}
但这不起作用。这是我当前的树枝代码:
<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 %}
我假设 error.car_models
是一个 布尔值 而 populate.car_models
是一个 字符串 .
{% 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 %}