3

好的,所以我有一个带有 2 个选项的选择表

$builder->add('type', 'choice', array(
    'label' => 'User type',
    'choices' => array('1' => 'Customer', '2' => 'Supplier'),
    'expanded' => true,
    'multiple' => false,
    'required' => false,
));

我想使用 twig 拆分视图中的选项以获得如下内容:

{{ form_widget(form.type/choice_1/) }}
some html stuf
{{ form_widget(form.type/choice_2/) }}

有什么建议吗?

4

2 回答 2

9

您需要将模板添加到表单中。这是文档: http ://symfony.com/doc/current/cookbook/form/form_customization.html

这里有多个示例: https ://github.com/phiamo/MopaBootstrapBundle/blob/master/Resources/views/Form/fields.html.twig

该字段适合您:

{% block choice_widget_expanded %}
{% spaceless %}
<div {{ block('widget_container_attributes') }}>
{% for child in form %}
    <label class="{{ (multiple ? 'checkbox' : 'radio') ~ (widget_type ? ' ' ~ widget_type : '') ~ (inline is defined and inline ? ' inline' : '') }}">
        {{ form_widget(child, {'attr': {'class': attr.widget_class|default('')}}) }}
        {{ child.vars.label|trans({}, translation_domain) }}
    </label>
{% endfor %}
</div>
{% endspaceless %}
{% endblock choice_widget_expanded %}

你可以做任何你想做的事,只要离开:{{ form_widget(child, {'attr': {'class': attr.widget_class|default('')}}) }}独自一人:)

  1. 您需要创建文件YourBundle/Resources/Form/fields.html.twig
  2. 粘贴上面的代码。
  3. 将主题添加到表单:{% form_theme form 'AcmeDemoBundle:Form:fields.html.twig' %}
  4. 并准备好摇滚!
于 2012-09-20T07:43:58.353 回答
2

定义的字段数:

{{ form_widget(form.type.0) }}{{ form_label(form.type.0) }}
    some html stuf
{{ form_widget(form.type.1) }}{{ form_label(form.type.0) }}

可变数量的字段:

{% for i in 0..form.type|length-1 %}
    {{ form_widget(form.type[i]) }}
    {{ form_label(form.type[i]) }}
{% endfor %}

当我们选择不按顺序的 id 时:

例如

$typeChoice = [
    "choice 1" => 2,
    "choice 2" => 5
]

{% for type in form.type %}
    {{ form_label(type) }}
    {{ form_widget(type) }}
{% endfor %}
于 2015-10-09T11:29:41.330 回答