我正在编写一个表单。我正在使用 Select2 允许用户在选择标签中选择多个选项。如果存在其他错误,我将用户重定向回窗体,并保留用户已键入或选择的值,以便他不必再次填写整个窗体。
字段上的其余部分一切都很好,因为我只需使用 request.post('input_name')
函数即可检索发布的信息。
当涉及到这些多个选择时,我知道我得到了一个数组。不知何故,如果我只进行以下测试,我知道数组中确实有值发布:
{% if request.post('select2inputMultiple') %}
<p>Data have been posted from select2 multiple</p>
{% endif %}
但是,如果我尝试显示(输出)这样的数据:
{{request.post('select2inputMultiple')}}
它会引发以下错误: An exception has been thrown during the rendering of a template ("Array to string conversion")
如何访问该数组的项目?
好吧,看起来它正在工作,我正在尝试使用这样的foreach函数:
{% if request.post('select2inputMultiple') %}
<p>Data have been posted from select2 multiple</p>
{% for single in request.post('select2inputMultiple') %}
value: {{single}}
{% endfor %}
{% endif %}
它正在根据需要输出数据!
假设您的输入名为 select2inputMultiple[]
,request.post('select2inputMultiple')
是一个数组(如错误所示)。如果没有中介将数组转换为字符串,则无法在页面上显示数组。从 Twig 查看值的最简单方法是使用 dump
方法,该方法映射到 var_dump
。所以你会做的
{{ dump(request.post('select2inputMultiple')) }}
假设您有一个这样的选择结构:
<select name="select2inputMultiple[]">
{% for option in options %}
<option value="{{ option.id }}">{{ option.name }}</option>
{% endfor %}
</select>
从该数组中选择这些选项的最简单方法是:
<select name="select2inputMultiple[]">
{% for option in options %}
<option value="{{ option.id }}"
{% if option.id in request.post('select2inputMultiple') %}
selected
{% endif %}
>{{ option.name }}</option>
{% endfor %}
</select>