symfony2 form templating
I want to render a form. HTML for a field row should be like this:
<li class="text">
<label for="fieldname">
<div>
<input type="text" ... />
</div>
</l开发者_Python百科i>
when the field type is text the li.class have to be the same.
I overwrite the field_row block:
{% block field_row %}
{% spaceless %}
<li class="text">
{{ form_label(form, label|default(null)) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</li>
{% endspaceless %}
{% endblock field_row %}
but how to replace the class value?
You can try to attach a public member to your FormType class (If present...) and call it from the twig template.
Maybe also the attributes array of a form can be accessed in a twig template...
class YourType extends AbstractType
{
public $class = 'text';
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('fieldname');
}
//...
}
And
{% block field_row %}
{% spaceless %}
<li class="{{ form.class }}">
{{ form_label(form, label|default(null)) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</li>
{% endspaceless %}
{% endblock field_row %}
Just replace the "field" word with the name of the type you want to modify.
You do it like this for text fields, but it's the same for any type:
{% block text_row %}
{% spaceless %}
<li class="text">
{{ form_label(form, label|default(null)) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</li>
{% endspaceless %}
{% endblock text_row %}
or like this for textareas:
{% block textarea_row %}
{% spaceless %}
<li class="textarea">
{{ form_label(form, label|default(null)) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</li>
{% endspaceless %}
{% endblock textarea_row %}
The important part is the block name, it should be the same as the name of the type you want to modify. The "field_row" is the default for all field types if there is no exact matching name.
This also works for form-types you defined yourself (the ones that inherit from AbstractType, that's why it's important you add a name to your form-types, see http://symfony.com/doc/2.0/book/forms.html#creating-form-classes).
精彩评论