Symfony2树枝形成

时间:2015-09-14 14:47:22

标签: forms symfony twig

Symfony2在渲染表单时使用一些树枝模板。 特别是,为了呈现选择表单字段,symfony2使用以下代码片段(来自 form_div_layout.html.twig ):

{%- block choice_widget_collapsed -%}
    {%- if required and placeholder is none and not placeholder_in_choices and not multiple -%}
        {% set required = false %}
    {%- endif -%}
    <select {{ block('widget_attributes') }}{% if multiple %} multiple="multiple"{% endif %}>
        {%- if placeholder is not none -%}
            <option value=""{% if required and value is empty %} selected="selected"{% endif %}>{{ placeholder != '' ? placeholder|trans({}, translation_domain) }}</option>
        {%- endif -%}
        {%- if preferred_choices|length > 0 -%}
            {% set options = preferred_choices %}
            {{- block('choice_widget_options') -}}
            {%- if choices|length > 0 and separator is not none -%}
                <option disabled="disabled">{{ separator }}</option>
            {%- endif -%}
        {%- endif -%}
        {%- set options = choices -%}
        {{- block('choice_widget_options') -}}
    </select>
{%- endblock choice_widget_collapsed -%}

在我的应用程序中,我想创建一个新的表单类型,它扩展了默认的折叠选择类型,但是选项列表具有自定义格式。

换句话说,对于我的表单字段类型,名为 places_widget ,扩展 choice_widget_collapsed 块,但重新定义 choice_widget_options

我已经尝试过:

/* My first attempt */
{%- block places_widget -%}
    {% block choice_widget_options %}
      {{ block('choice_places_widget_options') }}
    {% endblock choice_widget_options %}

    {{ block('choice_widget_collapsed') }}
{%- endblock places_widget -%}

/* My other attempt */
{%- block places_widget -%}
    {{ block('choice_widget_collapsed', { 'choice_widget_options' => choice_places_widget_options }) }}
{%- endblock places_widget -%}

/* together with */
{%- block choice_places_widget_options %}
    // code here
{%- endblock choice_places_widget_options -%}

这两种解决方案都没有起作用,实际上我觉得我做错了。

有没有人知道如何实现目标? 提前谢谢

1 个答案:

答案 0 :(得分:0)

可以使用主题自定义表单(请参阅此处的文档:http://symfony.com/doc/current/cookbook/form/form_customization.html#form-theming-in-twig

在您的情况下,您似乎需要加载自己的主题:     {% form_theme form _self %}

请注意,您可以将这些块外部化为另一个文件(请参阅http://symfony.com/doc/current/cookbook/form/form_customization.html#method-2-inside-a-separate-template以了解如何执行此操作)