简体   繁体   English

Symfony2 FormBuilder:如何添加和属性到多个表单域

[英]Symfony2 FormBuilder: How to add and attribute to multiple form fields

I want to add a stylesheet class attribute to most of the fields, but not all. 我想在大多数字段中添加样式表类属性,但不是全部。

public function buildForm(FormBuilder $builder, array $options)
{
    $builder
        ->add('name_short', null, array('attr' => array('class' => 'rtl')) )
        ->add('name_long')
        ->add('profile_education')
        ->add('profile_work')
        ->add('profile_political')
        ->add('twitter')
        ->add('facebook')
        ->add('website')
    ;
}

Is there a simpler way than adding the attribute array('attr' => array('class' => 'rtl')) to every field? 有没有比将属性array('attr' => array('class' => 'rtl'))到每个字段更简单的方法?

Was looking for something like looping the fields and setting the attribute after adding the field to the builder. 在将字段添加到构建器之后,正在查找循环字段和设置属性之类的内容。

More like this (unfortunately there is no setOption method in FormBuilder): 更像是这样(不幸的是,FormBuilder中没有setOption方法):

foreach($builder->all() as $key => $value) {
    $value->setOption('attr', array('class' => 'rtl'));
}

Thanks for any pointers. 谢谢你的任何指示。

You can do this while constructing the form. 您可以在构建表单时执行此操作。 Simply hold the field names in an array. 只需将字段名称保存在数组中即可。 If you need to assign different field types, then use an associative array instead. 如果需要指定不同的字段类型,请改用关联数组。

public function buildForm(FormBuilder $builder, array $options)
{
    $fields = array('name_short', 'profile_education', 'profile_work', 'profile_political', 'twitter', 'facebook', 'website');

    foreach ($fields as $field) {
        $builder->add($fields, null, array('attr' => array('class' => 'rtl')));
    }
}

Came across this and remembered that I recently found a way that works. 遇到这个并记得我最近发现了一种有效的方法。
Basically iterating over all fields removing and re-adding them with merged options. 基本上迭代所有字段,删除并使用合并选项重新添加它们。
Take this example below. 以下面的例子为例。

public function buildForm(FormBuilder $builder, array $options)
{
    $builder
        ->add('name_short')
        ->add('name_long')
        ->add('profile_education')
        ->add('profile_work')
        ->add('profile_political')
        ->add('twitter')
        ->add('facebook')
        ->add('website')
    ;

    $commonOptions = array('attr' => array('class' => 'rtl'));

    foreach($builder->all() as $key => $field)
    {
        $options = $field->getOptions();
        $options = array_merge_recursive($options, $commonOptions);

        $builder->remove($key);
        $builder->add($key, $field->getName(), $options);
    }    
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM