简体   繁体   中英

Select with optgroup in Symfony 2.0

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.

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

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'
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM