Skip to content

How to set a class attribute to a Symfony2 form input

In Symfony2, you can set the class attribute of a form input by using the "attr" option in the form field configuration. For example, if you have a form field named "name" and you want to set its class attribute to "custom-class", you can do the following:

Example of setting the class attribute of a form input by using the "attr" option in Symfony2

php
$builder->add('name', TextType::class, array(
    'attr' => array('class' => 'custom-class'),
));

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

This sets the class attribute of the "name" field to "custom-class". You can also add multiple classes by adding them as a string of space-separated class names, like so:

Example of adding multiple classes by adding them as a string of space-separated class names in Symfony2

php
$builder->add('name', TextType::class, array(
    'attr' => array('class' => 'custom-class other-class'),
));

Also, you can use a FormType Extension to set the class attribute to all the form fields, this way you don't need to set the class attribute to each field one by one.

Dual-run preview — compare with live Symfony routes.