Reputation: 4188
I have a form that shows a drop-down menu of categories to choose from.
These categories are setup using the Gedmo Tree Extension, so a category can have child categories.
I have a custom query in the form builder that selects only the categories that belong to a specific group. However, I need to be able to show in the drop-down which categories are parents and which are children, e.g.
Parent Category 1
-- Child Category A
-- Child Category B
Parent Category2
-- Child Category C
Any idea how I can achieve this?
Also, how can I pass a variable to my query_builder, from the controller that is calling the formtype?
Upvotes: 1
Views: 5631
Reputation: 2505
Extend Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList and use it in formBuilder, for ex:
$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' => '----'
));
You have to overwrite: getEntity(), getEntities(), getIdentifierValues() and probably constructor too
Upvotes: 0
Reputation: 41
A few days ago I was looking to accomplish exactly the same thing ! I used Neurofr solution here : Symfony2,Doctrine Extensions Tree : Generating a "tree"-like dropdown Select list
And it's work. Now I will try to deactivate all options that got last children from the tree.
Upvotes: 1
Reputation: 9957
If you don't need to select the parent you can use the optgroup tag
<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>
Edit:
Symfony 2 supports the optgroup tag with arrays (untested, may contain errors):
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
));
}
Upvotes: 1