简体   繁体   中英

Symfony 3 Form EntityType field does not take empty choices

Following code keeps loading when $this->getChoices() return an empty array.

$builder->add('username', EntityType::class, array(
        'class' => 'ApiBundle:User',
        'choice_label' => 'name',
        'label' => 'User',
        'choices' => $this->getChoices(),
        'required' => false,
        'placeholder' => 'Select...',
));

I know the one solution would be to change EntityType with ChoiceType when choices are empty. However, would like to know any better fixes for this issue.

Below is the way I solved, please post your answer if someone knows the better way to do it.

 if($this->getChoices()) {
    $builder->add('username', EntityType::class, array(
            'class' => 'ApiBundle:User',
            'choice_label' => 'name',
            'label' => 'User',
            'choices' => $this->getChoices(),
            'required' => false,
            'placeholder' => 'Select...',
    ));
    } else {
    $builder->add('username', ChoiceType::class, array(
            'class' => 'ApiBundle:User',
            'choice_label' => 'name',
            'label' => 'User',
            'choices' => null,
            'required' => false,
            'placeholder' => 'Select...',
    ));
    }

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