我有一个表单,显示可供选择的类别下拉菜单。
这些类别是使用Gedmo树扩展设置的,因此类别可以包含子类别。
我在表单构建器中有一个自定义查询,它只选择属于特定组的类别。但是,我需要能够在下拉菜单中显示哪些类别是父母,哪些类别是孩子,例如
Parent Category 1
-- Child Category A
-- Child Category B
Parent Category2
-- Child Category C
知道如何实现这个目标吗?
另外,如何从调用formtype的控制器将变量传递给query_builder?
答案 0 :(得分:1)
如果您不需要选择父级,则可以使用optgroup标记
<select>
<optgroup label="Category 1">
<option>Option 1...</option>
<option>Option 2...</option>
<option>Option 3...</option>
</optgroup>
<optgroup label="Category 2">
<option>Option 1...</option>
<option>Option 2...</option>
<option>Option 3...</option>
</optgroup>
</select>
编辑:
Symfony 2支持带有数组的optgroup标记(未经测试,可能包含错误):
public function buildForm(FormBuilder $builder, array $options)
{
$category_choices = array(
array('Category 1' => array(
'1' => 'Option 1...',
'2' => 'Option 2...',
'3' => 'Option 3...'
)),
array('Category 2' => array(
'4' => 'Option 4...',
'5' => 'Option 5...'
))
);
$builder->add('category_list', 'choice', array(
'label' => 'Category',
'choices' => $category_choices
));
}
答案 1 :(得分:1)
前几天我想完成同样的事情!我在这里使用了Neurofr解决方案: Symfony2,Doctrine Extensions Tree : Generating a "tree"-like dropdown Select list
这是有效的。 现在,我将尝试停用从树中获取最后一个孩子的所有选项。
答案 2 :(得分:0)
扩展Symfony \ Bridge \ Doctrine \ Form \ ChoiceList \ EntityChoiceList并在formBuilder中使用它,例如:
$formBuilder
->add('parent', 'entity',
array(
'label' => 'Parent',
'em' => $em,
'class' => 'w3des\\Bundle\\SiteBundle\\Entity\\Menu',
'choice_list' => new MenuChoiceList($em, $group, $cfg['tree']),
'required' => false,
'empty_value' => '----'
));
你必须覆盖:getEntity(),getEntities(),getIdentifierValues()以及可能的构造函数