How to set a class attribute to a Symfony2 form in

2019-01-08 11:19发布

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

Something like this:

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

 {{ form_widget(form.birthdate) }}

I want this inputfield with the attribute class set to calendar

8条回答
SAY GOODBYE
2楼-- · 2019-01-08 12:02

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.

查看更多
疯言疯语
3楼-- · 2019-01-08 12:03

Like this:

{{ form_widget(form.description, { 'attr': {'class': 'form-control', 'rows': '5', 'style': 'resize:none;'} }) }}
查看更多
登录 后发表回答