I’m trying to display a select box with optgroups in Symfony 2.1.
My entity tree is : client has projects, project has parts (Part->getProject()->getClient())
I want to display my select box this way :
<select>
<optgroup>Client name
<option>Part name</option>
<!-- ... -->
</optgroup>
<!-- ... -->
</select>
The Symfony doc does not help a lot.
My working form builder (without group_by option) gives me a simple select :
$this->createFormBuilder()
->add('part','entity',array(
'class' => 'SGLFLTSPartBundle:Part',
'property' => 'name',
'query_builder' => function (\SGL\FLTS\PartBundle\Entity\PartRepository $er) {
return $er->createQueryBuilder('p');
}))
->getForm();
How do I add the group_by option to display client name? So far I’ve tried
'group_by' => 'project.client.name'
'group_by' => 'project.client'
'group_by' => 'ppc.name' // the DQL table alias
All give PHP errors
I’ve also tried to display the project name only as optgroup, no luck :
'group_by' => 'project'
'group_by' => 'project.name'
'group_by' => 'project.id' // throws no error, giving me <optgroup label="1"> ...
and tried adding project/client joins in the createQueryBuilder
$er->createQueryBuilder('p')->select('p, pp')->leftJoin('p.project','pp');
$er->createQueryBuilder('p')->select('p, pp.name')->leftJoin('p.project','pp')
// wrong
Thanks!
I had a similar problem today.
I imagine you’ve been seeing a lot of PHP errors related to the incorrect use of Objects as Array keys? This is caused by Symfony trying to use the whole related object as the array key in the grouped results array.
I’ll need to look further into it for a better solution but for the meantime this is what I’m using…
Add a new method to the
Partentity calledgetClientNamethat looks like this:Set the
group_byoption toclientNamein the form field builder:The idea behind the use of this extra method is to give Symfony a class method that it can call to get a string value to perform the grouping with.
If anyone else has a more elegant solution I’d be keen to see it.