Symfony2 Twig Form Shortcuts: 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 this? I tried to do this in the Twig extension, but I do not have access to the form_widget function.

Edit : I could do this using the form.name properties (including the parent form), but I would repeat the symfony code, that would be a very ugly big hack

+4
source share
1 answer

It makes more sense if you ask me to move attr to the form class:

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

Since I assume that for some of your fields you can use some kind of custom rendering:

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

You can also create a new type and configure it as described here:

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

You can even change the default rendering method and ask symfony to render the default placeholder tag using the field label string (details of including the form theme are globally covered by the link mentioned 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 %} 

That way you would restrict form_row (form.name) using the theme provided by symfony. Symfony aproach looks "very" DRY / DIE to me. Hope this helps.

+2
source

All Articles