Symfony2/Twig - 遍历选择选项遍历、选项、Twig

2023-09-07 09:39:54 作者:我的爱ペ有你才完美

显示select字段的常用方法是调用

Usual way of displaying select field is to call

{{ form_row(form.doctor_service_id, {'attr':{'class':'form-control'}}) }}

我想做两件事:

检查这个字段是否真的是一个选择字段遍历每个选项(值、名称).我知道 twig 迭代器是如何工作的,只是不知道如何访问 select 选项并将它们转换为它. Check if this field is actually a select field Iterate over every option (value, name). I know how twig iterator works, I just don't know how to access select options and cast them to it.

推荐答案

<select name="country"data-width="100%">
    {% for key,val in form.country.vars.choices %}
        <option value="{{ val.value }}" {{  form.country.vars.value == '' and key == 0 ? ' selected ' :(val.value == form.country.vars.value ? ' selected ' : '') }}>{{ val.label | trans }}</option>
    {% endfor %}
</select>