Skip to content
Advertisement

list display in choicEntity in symfony 5

I am not at all familiar with PHP, and still months with Symfony, I am developing a small project thanks to a tutorial and I have a problem that has blocked me for too long veil: I have a choiceType on a form which must display a list that comes from an array passed in the parameters of the createForm

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $choices = $options['choices'];
    $builder
        -> add ('month', ChoiceType::class, [
            'choices' => $choices,
      ]);
}

My array comes from

$months = $tagtimeRepository->group_month($chron); 
$choice = array(); 
foreach($months as $lang){ 
    $code = $lang->getMonth(); 
    $choice[] = $code; 
}

So here it is, the list displays 0, 1, 2, ..., but I would like to see 11, 8, 9, ...

Advertisement

Answer

As prompted in the documentation

The choices option is an array, where the array key is the item’s label and the array value is the item’s value

Source: https://symfony.com/doc/current/reference/forms/types/choice.html#choices, emphasis, mine

So you just have to swap your keys and values in your array and you should be good to go:

public function buildForm(FormBuilderInterface $builder, array $options)
{
     $builder->add('month', ChoiceType::class, [
         'choices' => [
             '11' => '0',
             '8'  => '1',
             '9'  => '3',
         ],
     ]);
 }

If you do get those values in this way from a database, as you prompted it later, you can still use array_flip in order to have the array in the correct way:

public function buildForm(FormBuilderInterface $builder, array $options)
{
     /**
      * array_flip would flip keys and value, effectively making the array 
      * [
      *      '11' => '0',
      *      '8'  => '1',
      *      '9'  => '3',
      * ]
      * out of 
      * [
      *      '0' => '11',
      *      '1' => '8',
      *      '3' => '9',
      * ]
      **/
     $builder->add('month', ChoiceType::class, [
         'choices' => array_flip($options['choices']),
     ]);
 }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement