Select with optgroup in Symfony 2.0
Asked Answered
S

2

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.

Singlet answered 3/9, 2012 at 8:28 Comment(4)
It seems to be fixed in sf2.1 (see the doc). Are you using sf2.0 or sf2.1?Mausoleum
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?Singlet
No don't close, there might have a workaround to have optgroup on sf2.0, but I don't know it.Mausoleum
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!Singlet
S
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

Scrabble answered 3/9, 2012 at 9:3 Comment(2)
Much like in symfony 1.x: array of array.Mausoleum
Perfect! Great alternative for using the entities.Historiographer
S
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'
));
Sulphurbottom answered 24/10, 2012 at 9:3 Comment(4)
how about self referencing. like Category and Sub Category?Balf
@Daskul sorry I don't understand what you mean.Sulphurbottom
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 categoryBalf
I would say this is not possible. Mainly because it is not allowed in HTML to nest <optgroup> element (see developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup "Note: Optgroup elements may not be nested.")Sulphurbottom

© 2022 - 2024 — McMap. All rights reserved.