20

In Symfony2, the select html component is rendered as a ChoiceType object, which is used indeed also for checkboxes and radiobuttons.

Does someone really know how to render a select with the optgroup option in Symfony2?

For sake of completeness, here I report an example of a select with the optgroup tag (example from w3cschools):

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select> 

Moreover, notice that there is a similar post here, but the answers are not convincing.

Community
  • 1
  • 1
JeanValjean
  • 17,172
  • 23
  • 113
  • 157
  • It seems to be fixed in sf2.1 ([see the doc](http://symfony.com/doc/master/reference/forms/types/entity.html#group-by)). Are you using sf2.0 or sf2.1? – j0k Sep 03 '12 at 08:33
  • SF2.0! But SF2.1 is at RC2 now! So, it is better to wait for the first 2.1 stable release... Should I cancel the question? – JeanValjean Sep 03 '12 at 08:36
  • No don't close, there might have a workaround to have optgroup on sf2.0, but I don't know it. – j0k Sep 03 '12 at 08:38
  • Honestly, I don't know If I will migrate to Symfony2.1. I don't know how much effort will be required doing the porting of the projects and plugins! – JeanValjean Sep 03 '12 at 08:40

2 Answers2

36

Do this:

$car_choices = array(
    'Swedish Cars' => array(
        'volvo' => 'Volvo',
        'saab' => 'Saab',
    ),
    'German Cars' => array(
        'mercedes' => 'Mercedes',
        'audi' => 'Audi'
    )
);

$form = $this->createFormBuilder()
        ->add('car', 'choice', array(
            'label' => 'Choose your car',
            'choices' => $car_choices,
            ))
        ->getForm();

Works for Symfony 2.0.x

Carlos Granados
  • 11,273
  • 1
  • 38
  • 44
16

It depends how your Entity is defined and how you group your entity. Assuming the grouping is done given a parameter in your object, let's say "brand". You can do:

$builder->add('cars', null, array(
  'group_by'=> 'brand'
));
Sylvain
  • 542
  • 6
  • 20
  • how about self referencing. like Category and Sub Category? – Jaime Sangcap Feb 23 '15 at 09:47
  • @Daskul sorry I don't understand what you mean. – Sylvain Feb 24 '15 at 15:12
  • self referencing relationship. you have an entity that has reference to the same entity type as its parent. Like on Category. I want all my categories in one database table but still able to make hierarchies. Ex. I will create category of Computer, Laptop, Desktop but I want Laptop and Desktop under the COmputer category – Jaime Sangcap Feb 25 '15 at 09:31
  • I would say this is not possible. Mainly because it is not allowed in HTML to nest `` element (see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup "Note: Optgroup elements may not be nested.") – Sylvain Feb 26 '15 at 03:19