Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

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

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:

 public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
                ->add('hours', null ,
                  array('attr'=> 
                             array(
                                 'placeholder'=>'Working Hours',
                                 'class'=>'ui-spinner-box') ) )
    }

In my code above the ui-spinner-box will be outputted for both label and input. It will even put placeholder for its label.

So how to make it create attr for label separately so I can output something like below :

<label class="MYCLASSFOR_LABEL"   for="input_id">Hours</label>
<input class="MYCLASSFOR_INPUTS"  type="text" id="input_id" name="" value="" >
question from:https://stackoverflow.com/questions/10919619/symfony2-how-to-make-a-form-label-class-attr-different-than-its-input

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'),
    ));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...