Symfony2选择形式分裂在树枝上

时间:2012-09-20 07:34:27

标签: forms symfony twig symfony-forms

好的,我有一个带有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/) }}

任何sugestions?

2 个答案:

答案 0 :(得分: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. 准备好摇滚!

答案 1 :(得分: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而不是按顺序时:

e.g

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

{% for type in form.type %}
    {{ form_label(type) }}
    {{ form_widget(type) }}
{% endfor %}