Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
470 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...