質問

I am generating the form in embedded controller action. And now i have faced the following problem. The Form Theming is not working in that case.

So what i have:

  1. The tempalte "page.html.twig"

    {% block content %}
    {% render 'MyBundle:Widget:index' %}
    {% endblock %}
    
  2. The indexAction() creates the form and rendering another template "form.html.twig" which is normally renders a form using form_row, form_rest and so on.

So, now i am trying to customize form theming, and here is my problem. When i put the code

{% form_theme form _self %}

in the page.html.twig, i got an error the the form variable does not exists. And its correct, the form var is created later in the embedded controller. But when i put the theming code in embedded template "form.html.twig", i got another error "Variable "compound" does not exist"

{% block form_label %}
{% spaceless %}
    {% if not compound %}
        {% set label_attr = label_attr|merge({'for': id}) %}
    {% endif %}
    {% if required %}
        {% set label_attr = label_attr|merge({'class': (label_attr.class|default('') ~ ' required')|trim}) %}
    {% endif %}
    {% if label is empty %}
        {% set label = name|humanize %}
    {% endif %}
    <label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %} {% if attr.tooltip is defined %}title="{{ attr.tooltip }}"{% endif %}>{{ label|trans({}, translation_domain) }}{% if required %}<span>*</span>{% endif %}</label>
{% endspaceless %}
{% endblock form_label %}

This part of code was copied from this file https://github.com/symfony/symfony/blob/2.1/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig

So tried someone to do something like this?

役に立ちましたか?

解決

Answering my question myself.

It was a small sentence in Symfony2 docs http://symfony.com/doc/current/book/forms.html

This {% form_theme form _self %} functionality will only work if your template extends another. If your template does not, you must point form_theme to a separate template.

So there are two solutions to solve this problem:

  1. move form theme code to the separate file and include it in a embedded template using

    {% form_theme form with 'fields.html.twig' %}
    
  2. leave the form theme code in the same template, where the form will be generated, but extend the template from some "form.html.twig" empty template.

I have only done the second way, and its works, but I am sure the first one will work as well.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top