简体   繁体   English

Symfony2 Twig表单的快捷方式:form_widget

[英]Shortcuts with Symfony2 Twig forms : form_widget

I would like to replace: 我要替换:

{{ form_errors(form.name) }}
{{ form_widget(form.name, { 'attr': {'placeholder': 'Nom'} }) }}

By: 通过:

{{ form.name|field('Nom') }}

How could I do that? 我该怎么办? I tried to do it in a Twig extension but I don't have access to the form_widget function. 我尝试在Twig扩展程序中执行此操作,但是无法访问form_widget函数。

Edit : I could do it with the form.name properties (that include the parent form) but I would repeat symfony code, it would be a very ugly big hack 编辑 :我可以使用form.name属性(包括父表单)来做到这一点,但我会重复symfony代码,这将是一个非常丑陋的大技巧

Makes more sense if you ask me to move the attr to your form class: 如果您要求我将attr移至表单类,则更有意义:

class SomeForm extends AbstractType {
      //.....
      $builder->add('name', 'text', array('attr' => array('placeholder'=>'Nom')));
}

Since i guess you need some custom rendering for some of your fields you can check: 由于我想您需要对某些字段进行自定义渲染,因此可以检查:

http://symfony.com/doc/2.0/cookbook/form/form_customization.html#how-to-customize-an-individual-field http://symfony.com/doc/2.0/cookbook/form/form_customization.html#how-to-customize-an-individual-field

You could also create a new type and customize it as explained here: 您还可以按照以下说明创建新类型并对其进行自定义:

http://symfony.com/doc/2.0/cookbook/form/form_customization.html#what-are-form-themes http://symfony.com/doc/2.0/cookbook/form/form_customization.html#what-are-form-themes

You could even change the default way of rendering and ask symfony to render your placeholder tag by default using the field's label string (the details of enabling the form theme globally are covered by the link referenced above): 您甚至可以更改默认的呈现方式,并要求symfony默认使用字段的标签字符串来呈现占位符标签(全局引用表单主题的详细信息已在上面引用的链接中涵盖):

{% block text_widget %}
    {% set type = type|default('text') %}
    <input type="text" {{ block('widget_attributes') }} value="{{ value }}" />
{% endblock field_widget %}

{% block widget_attributes %}
  {% spaceless %}
    {% for attrname,attrvalue in attr %}{{attrname}}="{{attrvalue}}" {% endfor %} placeholder="{{ label|trans }}"
  {% endspaceless %}
{% endblock widget_attributes %}

{% block form_row %}
  {% spaceless %}
    <div class="my-class">
        {{ form_errors(form) }}
        {{ form_widget(form) }}
    </div>
  {% endspaceless %}
{% endblock form_row %}

So you would limit yourself to a form_row(form.name) using the theming that symfony provides. 因此,您将使用symfony提供的主题将自己限制为form_row(form.name)。 Symfony's aproach looks "very" DRY/DIE to me. 对我来说,Symfony的方法看起来“非常”干/死。 Hope it helps. 希望能帮助到你。

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

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