gpt4 book ai didi

php - 添加类以在 Symfony FormBuilder 中选择选项

转载 作者:可可西里 更新时间:2023-10-31 23:18:57 24 4
gpt4 key购买 nike

在我的 Symfony 2 应用程序中,我使用 FormBuilder 创建一个表单,用于选择生成的文档中包含的数据。

$typeChoices = [
'001' => 'first factor',
'002' => 'another factor',
'003' => 'some surcharge',
'004' => 'custom discount',
'005' => 'another surcharge'
];

$formDownload = $this->createFormBuilder(array())
->add('category', 'entity', array(
'class' => 'MyApp\CategoryBundle\Entity\Category',
'choice_label' => 'name'
))
->add('type', 'choice', array(
'choices' => $typeChoices,
'multiple' => true
))
->add('download', 'submit', array(
'attr' => array(
'class' => 'btn-primary'
),
))
->setAction($this->generateUrl('myapp_data_download'))
->getForm();

$typeChoices 数据是从 EntityRepository 加载的 - 我只是简化了这个演示的代码。

这样就生成了一个选择框:

<select multiple="multiple" class="form-control" required="required" name="form[type][]" id="form_type">
<option value="001">first factor</option>
<option value="002">another factor</option>
<option value="003">some surcharge</option>
<option value="004">custom discount</option>
<option value="005">another surcharge</option>
</select>

如何为每个选项添加一个class属性?它必须基于来自 EntityRepository 的原始数据的属性创建。直到现在,我无法在使用 FormBuilder 时将 class 属性添加到 option 并且我想避免创建表单手动标记。

最佳答案

Symfony 2.7 中的新功能:Choice form type refactorization

In Symfony 2.7 this form type has been completely refactored to support dynamic generation for labels, values, indexes and attributes. This is now possible thanks to the new options choice_label, choice_name, choice_value, choice_attr, group_by and choices_as_values.

例如,您可以生成动态选择标签

示例:

$builder->add('attending', 'choice', array(
'choices' => array(
'yes' => true,
'no' => false,
'maybe' => null,
),
'choices_as_values' => true,
'choice_label' => function ($allChoices, $currentChoiceKey) {
return 'form.choice.'.$currentChoiceKey;
},
));

在您的情况下,您希望操纵每个选项的属性类

示例:

$builder->add('attending', 'choice', array(
'choices' => array(
'Yes' => true,
'No' => false,
'Maybe' => null,
),
'choices_as_values' => true,
'choice_attr' => function ($allChoices, $currentChoiceKey) {
if (null === $currentChoiceKey) {
return array('class' => 'text-muted');
}
},
));

希望对您有所帮助。

关于php - 添加类以在 Symfony FormBuilder 中选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31608266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com