How to set a class attribute to input a Symfony2 form

How to set HTML class attribute to <input> form using FormBuilder in Symfony2 ?

Something like that:

 ->add('birthdate', 'date',array( 'input' => 'datetime', 'widget' => 'single_text', 'attr' => array( 'class' => 'calendar' ) )) {{ form_widget(form.birthdate) }} 

I need this input field with class attribute set to calendar

+53
input php forms symfony formbuilder
Jul 18 2018-11-18T00:
source share
7 answers

You can do this from the branch template:

 {{ form_widget(form.birthdate, { 'attr': {'class': 'calendar'} }) }} 

From http://symfony.com/doc/current/book/forms.html#rendering-each-field-by-hand

+104
Jul 18 '11 at 16:26
source share

You can do this with FormBuilder. Add this to the array in FormBuilder:

 'attr'=> array('class'=>'span2') 
+106
Mar 13 2018-12-12T00:
source share

Acyra's answer leads the right way if you want to set attributes inside the controller, but has a lot of inaccuracies.

Yes, you can do this directly using FormBuilder using the attr attribute (here presented here for version 2.1 and here for version 2.0 ) into an array of parameters as follows:

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

It is not true that "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 version 2.1).

In addition, since the attr attribute is the array itself, you can pass any HTML attribute that you want to display for this field. This is very useful if you want to pass HTML5 data- attributes.

+27
Nov 13 '12 at 10:20
source share
 {{ form_widget(form.content, { 'attr': {'class': 'tinyMCE', 'data-theme': 'advanced'} }) }} 
+4
Dec 10 '15 at 6:02
source share

Like this:

 {{ form_widget(form.description, { 'attr': {'class': 'form-control', 'rows': '5', 'style': 'resize:none;'} }) }} 
+3
May 20 '16 at 9:47 a.m.
source share

You can add it to the parameters of your form class:

 public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle\Entity\MyEntity', 'attr' => array( 'class' => 'form-horizontal' ) )); } 
+1
Jul 24 '17 at 10:28
source share

Displays the HTML widget for the specified field. If you apply this to the entire form or collection of fields, each row of the baseline will be displayed.

{# render a field row, but display a label with text "foo" #} {{ form_row(form.name, {'label': 'foo'}) }}

The second argument to form_row () is an array of variables. The templates provided in Symfony only allow you to override the shortcut, as shown in the above example.

For more information on variable variables, see "More information on form variables."

0
Aug 25 '17 at 23:25
source share



All Articles