I want to add a class to certain input or label elements in a Symfony application.
I can do something like this in a form on the Twig level:
<div class="row">
{{ form_label(form.subject) }}
{{ form_widget(form.subject, { 'attr': {'class': 'c4'} }) }}
</div>
This works fine. But I have to setup and write out the whole template for every form manually. And I actually want to use:
{{ form_widget(form) }}
So, I was thinking, how could I add a CSS class for a label or an input somewhere in the FormType:
class SystemNotificationType extends AbstractType {
public function buildForm(FormBuilder $builder, array $options) {
$builder->add('subject', 'text', array(
'label' => 'Subject'
));
I think this might be more useful, as you can configure the whole form in one place.
How can this be done? Maybe I’m thinking about it the wrong way.
The class of a field is part of the presentation layer of your application, so it is best to create a twig theme for your forms:
Create a file
fields.html.twiginResources/views/Formof your Bundle and define how your form row will be formated, for example:If you want to customize only certain field, for example the field
fieldNameof the formformName, customize the row:EDIT: customize only the field:
Then in all the form templates you want it use this theme add:
This is explained in depth in the cookbook