在Symfony

时间:2015-08-07 16:34:27

标签: symfony

我有一个symfony页面,我在其中显示一个表单,我想添加一个  *在所有必填字段的标签中。

所以我有我的form.php.twig,看起来像这样:

{% extends "::layout.php.twig" %}

{% block body %}

    <div class="row">

    {% use 'form_div_layout.html.twig' with form_label as base_form_label %}
    {% block form_label %}
        {{ block('base_form_label') }}

        {% if required %}
            <span class="required" title="This field is required">*</span>
        {% endif %}
    {% endblock %}
    </div>

{% endblock %}

我遵循了symfony cookbook的确切文档,了解如何自定义标签,http://symfony.com/doc/current/cookbook/form/form_customization.html#cookbook-form-theming-methods

但我一直收到这个错误

  

第206行的form_div_layout.html.twig中不存在变量“label”

我的form.php.twig的代码中没有任何标签变量,所以我不明白为什么会出现这个错误。当我删除

  

{{block('base_form_label')}}

我得到了

  

ATPlatformBundle中不存在变量“required”:Session:create.php.twig

任何人都可以帮我这个吗?我不知道我的错误在哪里?我不是要用css来定制它,而是添加*。

我在第206行查看了form_div_layout.html.twig,这就是

{%- block form_label -%}
    {% if label is not sameas(false) -%}
        {% 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 -%}
            {%- if label_format is not empty -%}
                {% set label = label_format|replace({
                    '%name%': name,
                    '%id%': id,
                }) %}
            {%- else -%}
                {% set label = name|humanize %}
            {%- endif -%}
        {%- endif -%}
        <label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>{{ translation_domain is sameas(false) ? label : label|trans({}, translation_domain) }}</label>
    {%- endif -%}
{%- endblock form_label -%}

提前谢谢。

3 个答案:

答案 0 :(得分:3)

您是否尝试过在表单构建器中定义标签?!以下字段是必填字段,因为除非您提及required =&gt; false,您的字段将根据需要呈现。 类似的东西:

->add('name', 'text', array('label' => '* name'))

答案 1 :(得分:0)

使用Twig,您必须在使用之前测试变量的存在:

变量&#34;必需&#34;不存在

{% if required is defined and ... }

您需要对此进行测试,因为您并不总是需要字段。

如果您想了解更多信息,请阅读以下文档页面:

http://twig.sensiolabs.org/doc/tests/defined.html

答案 2 :(得分:0)

好的,最后,我没有设法更改form.php.twig中的标签(这是我用来显示表单的模板),但我使用了另一种技术。

我创建了一个名为fields.php.twig的新文件,我将其放在MyBundle / Resources / views / Form中。

在我的fields.php.twig的开头,我添加了

{% extends 'form_div_layout.html.twig' %} 

在它之下,我添加了

{% block form_label %}
        {{ parent() }}
        {% if required %}
            <span> * </span>
        {% endif %}
{% endblock form_label %}

然后在我的form.php.twig中,我添加了

{% form_theme form 'MyBundle:Form:fields.php.twig' %}
{{ form_start(form) }}

Myform here with {{ form_label(form.property) }}

 {{ form_errors(form.property) }}
 {{ form_widget(form.property) }}

{{ form_end(form) }}

它完美无缺,但我必须创建fields.php.twig。

相关问题