Symfony2/Twig - 遍历选择选项

2022-01-22 00:00:00 php symfony twig

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

Usual way of displaying select field is to call

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

我想做两件事:

  1. 检查这个字段是否真的是一个选择字段
  2. 遍历每个选项(值、名称).我知道 twig 迭代器是如何工作的,只是不知道如何访问 select 选项并将它们转换为它.
  1. Check if this field is actually a select field
  2. 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>

相关文章