简体   繁体   中英

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.

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

Makes more sense if you ask me to move the attr to your form class:

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

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

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):

{% 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's aproach looks "very" DRY/DIE to me. Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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