Symfony2,如何使表单标签的类/属性与​​其输入不同? [英] Symfony2, How to make a form label class/attr different than its input?

查看:51
本文介绍了Symfony2,如何使表单标签的类/属性与​​其输入不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个带有标签和输入的表单,但是它们的类别应该不同.下面的代码为具有相同attr的输入创建标签:

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

在我上面的代码中,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.

那么如何使其分别为标签创建attr,这样我就可以输出如下内容:

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="" >

推荐答案

  • attr:键值数组,将在字段上以HTML属性的形式呈现
  • label_attr:一个键值数组,将在标签上显示为HTML属性
  • 您可以在树枝模板或表单构建器中设置这些属性:

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

    树枝模板:

    • 用于symfony 2.1和更高版本:

    • for symfony 2.1 and newer use:

    {{ form_label(form.hours, null, {'label_attr': {'class': 'foo'}}) }}
    

  • 在旧版symfony 2.0中,它曾经是

  • 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'} }) }}
    

  • 表单构建器

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

    这篇关于Symfony2,如何使表单标签的类/属性与​​其输入不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆