phptwitter-bootstrapformssymfonysymfony-2.8

Symfony Add bootstrap form-control class


I'm using symfony 2.8, I have created one registration form, I want to add bootstrap form-control class to both password and repeat password form fields.

$builder 
->add('name', TextType::class,array(
    'attr' => array(
        'class' => 'form-control'
    )
))  
-> add('plainPassword', RepeatedType::class, array(
    'type' => PasswordType::class,
    'first_options'  => array('label' => 'Password'),
    'second_options' => array('label' => 'Repeat Password'),
    'attr' => array('class' => 'form-control')
));

Incase of 'name' field its working BUT for password fields the class is not adding. How can I add 'form-control' class for password fields. Any help is much appreciated. Thanks.


Solution

  • There are two ways of doing this. The first is to use options, which will pass the options down to each of the underlying fields:

    ->add('plainPassword', RepeatedType::class, array(
        'type' => PasswordType::class,
        'first_options'  => array('label' => 'Password'),
        'second_options' => array('label' => 'Repeat Password'),
        'options' => array('attr' => array('class' => 'form-control'))
    ));
    

    You can also add the class in the first_options and second_options field, like so. This would be useful if you had options that were specific to each field or you wanted to override something from the main options.

    ->add('plainPassword', RepeatedType::class, array(
        'type' => PasswordType::class,
        'first_options'  => array(
            'label' => 'Password',
            'attr' => array('class' => 'form-control')
        ),
        'second_options'  => array(
            'label' => 'Password',
            'attr' => array('class' => 'form-control-override')
        ),
        'attr' => array('class' => 'form-control')
    ));
    

    Also, as of Symfony 2.6 it has has built-in Bootstrap form theme support to where you shouldn't have to be adding these classes to all of your fields manually.