简体   繁体   English

如何更改收集表单字段类型中的值和选择的标签?

[英]how change value and label of choice in collection form field type?

I have collection field type like this: 我有这样的集合字段类型:

$defaultData = array('attendances' => array('5', '4'));
    $form = $this->createFormBuilder($defaultData)
        ->add('choice', 'text')

        ->add('email', 'email')
        ->add('message', 'textarea')
        ->add('attendances', 'collection', array(
            'type'  => 'choice',

            'options'  => array(

                'choices'   => array('1' => 'حاضر', '0' => 'غایب'),
            ),
        ))
        ->add('send', 'submit')
        ->getForm();

what I get is this: 我得到的是:

在此处输入图片说明

See what labels of choices are(0 and 1) and also their input name attribute, what I want is to change label and input name attr so how can i change $defaultData for this? 查看选项的哪些标签是(0和1),以及它们的输入名称属性,我想要更改标签和输入名称attr,所以我如何为此更改$ defaultData?

Ok you can do this with data attribute as array, you can read more about it here 好的,您可以使用data属性作为数组来执行此操作,您可以在此处了解更多信息

Example with your code: 您的代码示例:

$defaultData = array('attendances' => 
   array('key' => '5', 'key2' => '4')
);
$form = $this->createFormBuilder($defaultData)
    ->add('choice', 'text')
    ->add('email', 'email')
    ->add('message', 'textarea')
    ->add('attendances', 'collection', array(
            'type'  => 'choice',

            'options'  => array(

                'choices'   => array('1' => 'حاضر', '0' => 'غایب'),
            ),
            'data' => $defaultData['attendances']
        ))
    ->add('send', 'submit')
    ->getForm();

result: 结果:

name="form[attendances][key]"
name="form[attendances][key2]"

and label also key and key2 并标记keykey2

I'd suggest that if you're going to create a select, you use the 'choice' type directly: 我建议如果您要创建一个选择,请直接使用'choice'类型:

->add('attendances', 'choice', array(
                    'choices' => array('1' => 'حاضر', '0' => 'غایب'),))

Hope it helps. 希望能帮助到你。

UPDATE 更新

You can use a predefined array to populate the choices. 您可以使用预定义的数组来填充选择。 You can also set the default using the data attribute. 您也可以使用data属性设置默认值。

$defaultData = array('attendances' => array('5' => 'One option', '4' => 'Another option'));

...
->add('attendances', 'choice', array(
                        'choices' => $defaultData["attendances"],
                        'data' => '5',))// just in case you want a preselected choice, in this case, key 5 will appear selected by default.
...

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

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