Symfony2, How to make a form label class/attr different than its input?

后端 未结 4 901
忘了有多久
忘了有多久 2021-01-30 05:31

I would like to build a form with label and inputs, but the class of them should be different. Code below creates the label for the input with same attr:

 publi         


        
4条回答
  •  猫巷女王i
    2021-01-30 05:45

    As mentioned in the documentation:

    • attr : A key-value array that will be rendered as HTML attributes on the field
    • label_attr: A key-value array that will be rendered as HTML attributes on the label

    You can set those attributes in twig template or in form builder:

    Twig template:

    • for symfony 2.1 and newer use:

      {{ form_label(form.hours, null, {'label_attr': {'class': 'foo'}}) }}
      
    • in the legacy symfony 2.0 it used to be

      {{ form_label(form.hours, { 'label_attr': {'class': 'MYCLASSFOR_LABEL'} }) }}
      {{ form_widget(form.hours, { 'attr': {'class': 'MYCLASSFOR_INPUTS'} }) }}
      

    Form builder

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('hours', null, array(
            'label_attr' => array('class' => 'MYCLASSFOR_LABEL'),
            'attr'       => array('class' => 'MYCLASSFOR_INPUTS'),
        ));
    }
    

提交回复
热议问题