How to set a class attribute to a Symfony2 form input

前端 未结 8 1840
生来不讨喜
生来不讨喜 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:03

    Renders the HTML widget of a given field. If you apply this to an entire form or collection of fields, each underlying form row will be rendered.

    {# 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 to override the label as shown in the example above.

    See "More about Form Variables" to learn about the variables argument.

    0 讨论(0)
  • 2020-11-30 00:04

    You can do this from the twig template:

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

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 00:06

    You can add it in the options of your form class:

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\MyEntity',
            'attr' => array(
                'class' => 'form-horizontal'
            )
        ));
    }
    
    0 讨论(0)
  • 2020-11-30 00:11
    {{ form_widget(form.content, { 'attr': {'class': 'tinyMCE', 'data-theme': 'advanced'} })  }}
    
    0 讨论(0)
  • 2020-11-30 00:15

    Like this:

    {{ form_widget(form.description, { 'attr': {'class': 'form-control', 'rows': '5', 'style': 'resize:none;'} }) }}
    
    0 讨论(0)
提交回复
热议问题