How to add style to a form type in symfony?

1.1k Views Asked by At

I have this registration page formType that's like this:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('email')
        ->add('username')
        ->add('agreeTerms', CheckboxType::class, [
            'mapped' => false,
            'constraints' => [
                new IsTrue([
                    'message' => 'You should agree to our terms.',
                ]),
            ],
        ])
        ->add('plainPassword', PasswordType::class, [
            // instead of being set onto the object directly,
            // this is read and encoded in the controller
            'mapped' => false,
            'constraints' => [
                new NotBlank([
                    'message' => 'Please enter a password',
                ]),
                new Length([
                    'min' => 6,
                    'minMessage' => 'Your password should be at least {{ limit }} characters',
                    // max length allowed by Symfony for security reasons
                    'max' => 4096,
                ]),
            ],
        ])

And I want to add bootstrap classes to these fields, How do I do that?

1

There are 1 best solutions below

0
Jason Stephenson On

You have 2 ways, if you want complete control over the classes and styling used you need to change to the following

->add('email', EmailType::class, array('attr'=>['class'=>'form-control']))

You can learn about form types here: https://symfony.com/doc/current/reference/forms/types.html

Using a type will add client side validation to the users input prior to letting the form submit.

If you want to avoid adding your own styling then twig actually has themeing built in, this will take care of everything for you and is available for all versions of bootstrap, this does not add the css files but you should already have those included in your page.

https://symfony.com/doc/current/form/form_themes.html

Just add the following line before you embed your form in your template

{% form_theme form 'bootstrap_4_layout.html.twig' %}