在我的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
为每个属性添加一个属性option
?必须基于来自的原始数据的属性来创建它EntityRepository
。到现在为止,我没能到添加class
属性来option
使用,当sFormBuilder
和我想避免手动创建的形式标记。
Symfony 2.7的新功能:选择表单类型重构
在Symfony 2.7中,此表单类型已完全重构,以支持标签,值,索引和属性的动态生成。现在有了新的选项choice_label,choice_name,choice_value,choice_attr,group_by和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');
}
},
));
希望它会有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句