[英]How to set as selected a new value from a select list with select2 and Twig templating?
我一直在努力使它起作用。
我有一個下拉菜單(通過使用HTML select標簽和select2.js)。 在數據庫中,我有兩個值,分別是這些值和這些值:
[{"type":"value1"},{"type":"value2"}]
我使用Twig顯示數據如下:
<select multiple="" style="width: 100%" name="type" id="types" class="select2 req_place form-control input-sm">
{% for type in types %}
<option value="{{type.type}}" {% if request.post('type')==type.type %}selected{% endif %}{% if proyecto_o.type==type.type and request.post('type') is empty %}selected{% endif %}>{{type.type}}</option>
{% endfor %}
</select>
這很好。 例如,如果表單由於另一個字段的驗證失敗而返回錯誤,則先前選擇的選項將顯示為選中狀態。
但是,如果用戶鍵入一個新值(允許),如下所示:
$("#types").select2({
placeholder: "Seleccione...",
allowClear: true,
tags: true, /*This allows the user to type a new value*/
language: "es",
maximumSelectionLength: 1,
});
新值不會顯示為選定的值。 我嘗試了多種方法來解決此問題,但我找不到解決方法。
例如,在我的嘗試之一中,如果我添加以下代碼
確實,新值仍然顯示為選定的值,但是,如果我從數據庫中選擇了一個已經存在的值,則它會顯示為選定值的兩倍! 我已經嘗試通過檢查數組中是否存在新值,但是仍然無法正常工作。
<select multiple="" style="width: 100%" name="type" id="types" class="select2 req_place form-control input-sm">
{% for type in types %}
<option value="{{type.type}}" {% if request.post('type')==type.type %}selected{% endif %}{% if proyecto_o.type==type.type and request.post('type') is empty %}selected{% endif %}>{{type.type}}</option>
{% endfor %}
{% if request.post('type') not in types %}
<option value="{{request.post('type')}}" selected>{{request.post('type')}}</option>
{% endif %}
</select>
即使我假裝檢查數組中是否不存在此新類型的值以將其放入下拉菜單中選擇的值,但它仍無法正常工作,因為如果我選擇了數據庫中已存在的值,它將出現兩次選擇。 如果我選擇一個新的,則一旦選擇它就會出現,這很好。
有任何解決辦法嗎? 如何使數據庫中那些已經存在的值不被選中兩次?
解決了
我發現了如何通過使用標志使其工作。
<!-- Types-->
{% set type_flag = 0 %}
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group {% if errors.has('type') %} has-error {% elseif request.post('type')%}has-success{% endif %}">
<label for="types" class="control-label{% if proyecto_o.type %} text-primary{% endif %}">type</label>
<select multiple="" style="width: 100%" name="type" id="types" class="select2 req_place form-control input-sm">
{% for type in types %}
<option value="{{type.type}}" {% if request.post('type')==type.type %}selected{% endif %}{% if proyecto_o.type==type.type and request.post('type') is empty %}selected{% endif %}>{{type.type}}</option>
{% if request.post('type')==type.type %}{% set type_flag=1 %}{% endif %}
{% if proyecto_o.type==type.type and request.post('type') is empty %}{% set type_flag=1 %}{% endif %}
{% endfor %}
{% if type_flag==0 and request.post('type') %}
<option value="{{request.post('type')}}" selected>{{request.post('type')}}</option>
% endif %}
</select>
{% if errors.has('type') %} <p class="help-block bg-danger">{{ errors.first('type') }}</p> {% endif %}
<p class="help-block">Flag: {{ type_flag }}</p>
</div>
</div>
現在,新值和已經注冊的值都顯示為選中狀態。
如果其他人有更好的方法,我將把您的答案標記為被接受的答案並被贊成。 沒問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.