Teshan N.
Teshan N.

Reputation: 2535

Symfony forms entity type with custom optgroup

I have a Symfony form with select boxes that lists down its options from an entity. But how can I list the database records (options) inside an <optgroup> which I manually specify (label of the optgroup)?

$form = $this->createFormBuilder()
    ->add('type', EntityType::class, array(
        'required' => true, 
        'class' => 'AppBundle:Types', 
        'choice_label' => 'name', 
        'empty_value' => 'Type',
    ));

The optgroup label is "What is the Type?" and I need to list the above data inside this optgroup.

Upvotes: 2

Views: 1923

Answers (2)

MaZaN
MaZaN

Reputation: 117

This can be solved by using the group_by option:

$form = $this->createFormBuilder()
    ->add('type', EntityType::class, array(
        'required' => true, 
        'class' => 'AppBundle:Types', 
        'choice_label' => 'name', 
        'empty_value' => 'Type',
        'group_by' => 'group',
));

You should add a field to AppBundle:Types which is named for example 'group'.

Upvotes: 3

Aurelien
Aurelien

Reputation: 1507

If this is a simple translation of a static string, I suggest you manually wrap your fields in an optgroup in your view (you could use a form theme for example), and set the label with your translated string. It would make more sense in my opinion.

If the label is dynamic, then I think this is what you're looking for : Symfony Doctrine - how to generate optgroup select form

Upvotes: 0

Related Questions