How to set a class attribute to a Symfony2 form input

前端 未结 8 1911
生来不讨喜
生来不讨喜 2020-11-29 23:27

How can I set the HTML class attribute to a form using the FormBuilder in Symfony2 ?

S

8条回答
  •  囚心锁ツ
    2020-11-30 00:04

    The answer by Acyra lead the right way if you want to set attributes inside the controller, but has many inaccuracies.

    Yes, you can do it directly with the FormBuilder by using the attr attribute (introduced here for the 2.1 version and here for the 2.0) to the array of options as follows:

    ->add('birthdate', 'date',array(
          'input' => 'datetime',
          'widget' => 'single_text',
          'attr' => array('class'=>'calendar')
     ))
    

    It is not true that the "functionality is broken". It works very well!

    It is not true that Symfony2 applies the HTML class attribute to both the label and the input (at least from the 2.1 version).

    Moreover, since the attr attribute is an array itself, you can pass any HTML attribute you want to render for the field. It is very helpful if you wanna pass the HTML5 data- attributes.

提交回复
热议问题