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条回答
霸刀☆藐视天下
2楼-- · 2019-01-08 11:39

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'
        )
    ));
}
查看更多
地球回转人心会变
3楼-- · 2019-01-08 11:47

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

查看更多
何必那么认真
4楼-- · 2019-01-08 11:51

You can to this in Twig or the FormClass as shown in the examples above. But you might want to decide in the controller which class your form should get. Just keep in mind to not have much logic in the controller in general!

    $form = $this->createForm(ContactForm::class, null, [
        'attr' => [
            'class' => 'my_contact_form'
        ]
    ]);
查看更多
迷人小祖宗
5楼-- · 2019-01-08 11:52
{{ form_widget(form.content, { 'attr': {'class': 'tinyMCE', 'data-theme': 'advanced'} })  }}
查看更多
做个烂人
6楼-- · 2019-01-08 11:56

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

'attr'=> array('class'=>'span2')
查看更多
成全新的幸福
7楼-- · 2019-01-08 11:58

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.

查看更多
登录 后发表回答