简体   繁体   English

symfony2和twig:获取表单字段的属性

[英]symfony2 and twig: get properties of form field

I am trying to create a form with sub-fields with symfony2. 我正在尝试创建一个带有symfony2子字段的表单。

In twig I render the form as 在树枝上,我将表单呈现为

    {{ form_start(form) }}

      {{ form_errors(form) }}
      <div>
      {{ form_label(form) }}
      {{ form_errors(form) }}

      {% for field in form %}
            {{ form_widget(field) }}
      {% endfor %}

      </div>

    {{ form_end(form) }}

However, I want to add some customization depending on the field I am rendering. 但是,我想根据我要渲染的字段添加一些自定义项。

What I want to achieve is something like this: 我想要实现的是这样的:

    {{ form_start(form) }}

      {{ form_errors(form) }}
      <div>
      {{ form_label(form) }}
      {{ form_errors(form) }}

      {% for field in form %}
          {% if field.label == "myvalue" %}  <-- this code is not working
            {# do something here #}
            {{ form_widget(field) }}
          {% endif %}
      {% endfor %}

      </div>

    {{ form_end(form) }}

I am not able to access the label of each of my sub-fields in twig. 我无法访问树枝中每个子字段的标签。
I think it is possible with something like {{ field.vars.something }} , but I did not manage to find any clear documentation about this. 我认为有可能使用{{field.vars.something}}之类的东西,但是我没有找到任何清晰的文档。

Can someone please help? 有人可以帮忙吗?
Thank you! 谢谢!

Edit: 编辑:

I actually found the answer to my question: It was indeed just {{ field.vars.label }} 我实际上找到了我的问题的答案:确实只是{{field.vars.label}}

and

          {% if field.vars.label == "myvalue" %}
            {# do something here #}
            {{ form_widget(field) }}
          {% endif %}

did the trick. 做到了。 However, I am still looking for some good documentation about this "vars" attribute in twig, and what can be retrieved with it. 但是,我仍在寻找有关树枝中此“ vars”属性以及可以使用该属性检索的一些好的文档。

Thanks! 谢谢!

You'll find more information at http://symfony.com/doc/current/reference/forms/twig_reference.html#more-about-form-variables 您可以在http://symfony.com/doc/current/reference/forms/twig_reference.html#more-about-form-variables中找到更多信息。

On that page you'll find a list of common form vars. 在该页面上,您会找到常见表格变量的列表。 You might also create custom vars by implementing the buildView method of a FormType. 您也可以通过实现FormType的buildView方法来创建自定义变量。 You can read an example at http://symfony.com/doc/current/cookbook/form/create_form_type_extension.html#adding-the-extension-business-logic 您可以在http://symfony.com/doc/current/cookbook/form/create_form_type_extension.html#adding-the-extension-business-logic中阅读示例

Hope it'll help 希望对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM