Search code examples
symfonyselectlabeldefaultoptgroup

Remove default optgroup label '0' in array select using Symfony2


I have a form that shows a drop-down menu to select a single value from an array defined in params.yml.

The dropdown displays '0' as an optgroup label above the list of values to be selected.

How can I get rid of this default label ?


Solution

  • You can replace the default OptGroup with something like the "Standard Hours" and "Other Hours" as defined below.

    $category_choices = array(
              'Standard Hours' => array(
                2 => '2',
                4 => '4',
                6 => '6',
                8 => '8'
              ),
              'Other Hours' => array(
                1 => '1',
                3 => '3',
                5 => '5',
                7 => '7',
                9 => '9',
                10 => '10'
              )
            );
    
            $builder
                ->add('hours', 'choice', array(
                  'choices' => $category_choices
             ));
    

    Alternatively, if you don't want OptGroup labels at all, and only selectable entries, you can just skip out on the nested arrays altogether.

    $builder
        ->add('hours', 'choice', array(
        'choices' => array(
            1 => '1',
            2 => '2',
            3 => '3',
            4 => '4'
        )
    ));
    

    In your case, you want something like:

    $builder
        ->add('hours', 'choice', array(
        'choices' => arrayFromParamsYML
    ));