symfony2 自定义表单选择选项 [英] symfony2 customize form select options

查看:27
本文介绍了symfony2 自定义表单选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个简单的表单来添加一个带有名称和颜色的活动.

I'm trying to do a simple form to add an activity with a name and a color.

所以我想用一些颜色数组制作一个列表,现在它正在工作,我有颜色的名称.
我可以向我的选择标签添加任何属性:

So I want to make a list with some an array of color, for now it is working I have the name of the color.
I can add any attribute to my select tag:

$form = $this->createFormBuilder($myclass)
->add('Colors','choice',array('label'=>'select some colors',
            'multiple'=>true,
            'choices'=>array(1=>'red', 2=>'blue', 3=>'green'),
            'attr'=>array('style'=>'width:300px', 'customattr'=>'customdata')
            ));

输出将是这样的:

<select name="select" style="width: 300px;" multiple="multiple" customattr="customdata">
   <option value="1">red</option>
   <option value="2">blue</option>
   <option value="3">green</option>
</select> 

但是如何将 selected="selected" 和我想要的任何属性添加到我的选择选项中?像这样:

But how can I add selected="selected" and any attribute I want to my select options ? like this:

<select name="select" style="width: 300px;" multiple="multiple" customattr="customdata">
   <option style="background-color: #F00;" value="1" selected="selected">red</option>
   <option style="background-color: #00F;" value="2" selected="selected">blue</option>
   <option style="background-color: #0F0;" value="3">green</option>
</select> 

我的问题是:如何通过 symfony FormBuilder 为 option 标签(不适用于 select 标签)添加自定义属性.
注意:我不想使用 JavaScript.我想使用 symfony2 FormBuilder 来自定义我的选择选项.

My question is: how can I add custom attr for option tag (not for select tag) by symfony FormBuilder.
NOTICE: I don't want to use JavaScript. I want to use symfony2 FormBuilder to customize my select options.

推荐答案

通常,字段的默认数据由存储在对象中的值决定.例如,如果

Usually, the default data of a field is determined by the value stored in your object. For example, if

class MyClass
{
    private $Colors = array(1, 2);
}

然后条目1"和2"(带有红色"和绿色"标签)将默认显示为选中状态.您还可以在将其传递给表单之前将此值存储在对象中:

then the entries "1" and "2" (with the labels "red" and "green") will be displayed as selected by default. You could also store this value in the object before passing it to the form:

$myObject->Colors = array(1, 2);

$form = $this->createFormBuilder($myObject)
    ...

最后一种可能是通过传递data"选项来覆盖存储在对象中的默认值:

The last possibility is to override the default value stored in the object by passing the "data" option:

$builder->add('Colors', 'choice', array(
    'label' => 'select some colors',
    'multiple' => true,
    'choices' => array(1 => 'red', 2 => 'blue', 3 => 'green'),
    'attr' => array('style' => 'width:300px', 'customattr' => 'customdata'),
    'data' => array(1, 2),
));

这篇关于symfony2 自定义表单选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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