我正在尝试呈现类似于 the SO question 的多项选择下拉列表使用 sonata_type_model
或 entity
类型。我有实体 Property
与 manyToMany
到 Feature
,即 FeatureType
的 oneToMany
。多选下拉列表正在属性创建表单中实现。
我找到了the group_by option 。但我使用 entity
收到警告,并使用 sonata_type_model
得到错误的渲染。
尝试 1
->add('features', 'entity', array(
'class' => 'MyBundle:Feature',
'multiple' => true,
'group_by' => 'featureType'
))
Warning: Illegal offset type in isset or empty in vendor/symfony/symfony/src/Symfony/Component/Form/ChoiceList/Factory/DefaultChoiceListFactory.php at line 334
尝试 2
->add('features', 'sonata_type_model', array(
'multiple' => true,
'btn_add' => null,
'group_by' => 'featureType'
))
它仅呈现下拉列表中的值,例如
尝试 3
我尝试了选择
,但出现了错误
->add('features', 'sonata_type_model', array(
'multiple' => true,
'required' => false,
'btn_add' => null,
'choices' => $this->getFeatureOptionsWithGroup()
))
Warning: get_class() expects parameter 1 to be object, array given in vendor/doctrine/common/lib/Doctrine/Common/Util/ClassUtils.php at line 58
尝试 4
我尝试了 choice_list
但出现错误
->add('features', 'sonata_type_model', array(
'multiple' => true,
'required' => false,
'btn_add' => null,
'choice_list' => $this->getFeatureOptionsWithGroup()
))
The option "choice_list" with value array is expected to be of type "null" or "Symfony\Component\Form\ChoiceList\ChoiceListInterface", but is of type "array" in vendor/symfony/symfony/src/Symfony/Component/OptionsResolver/OptionsResolver.php at line 888
方法getFeatureOptionsWithGroup()
返回这样的数组
array(
'Group 1' => array(
1 => 'Feature 1'
2 => 'Feature 2'
),
'Group 2' => array(
3 => 'Feature 3'
4 => 'Feature 4'
)
)
尝试 5
我使用 ModelChoiceList
更新了方法,但遇到了与使用 choices
相同的错误。
Warning: get_class() expects parameter 1 to be object, array given in vendor/doctrine/common/lib/Doctrine/Common/Util/ClassUtils.php at line 58
private function getFeatureOptionsWithGroup()
{
return new ModelChoiceList(
$this->modelManager,
'MyBundle:Feature',
null,
null,
$this->getRepository('MyBundle:Feature')->getFeatureOptionsWithGroup()
);
}
我希望我有机会在不覆盖模板的情况下渲染它。任何帮助将不胜感激。
最佳答案
使用类型实体
->add('features', 'entity', [
'class' => 'MyBundle:Feature',
'property' => 'name',
'choices' => $this->getFeatureOptionsWithGroup(),
'multiple' => true,
'required' => false,
'btn_add' => null,
])
确保您的函数 getFeatureOptionsWithGroup()
像这样返回
array(
'Group 1' => array(
1 => 'Feature Entity Object 1',
2 => 'Feature Entity Object 2',
),
'Group 2' => array(
3 => 'Feature Entity Object 3',
4 => 'Feature Entity Object 4',
)
)
关于php - 如何使用 "sonata_type_model"或 symfony "entity"渲染带有选项组的多项选择下拉列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31216828/