Symfony 3 Form EntityType字段不采用空选择

时间:2018-01-18 18:51:36

标签: php forms symfony entity

以下代码在$ this-> getChoices()返回空数组时继续加载。

// Set the alarm to start at approximately next year
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int year = calendar.get(Calendar.YEAR);
calendar.set(Calendar.YEAR, year + 1);

alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 0, alarmIntent);

我知道一个解决方案是在选项为空时用 ChoiceType 更改 EntityType 。但是,想知道对此问题的任何更好的修复。

1 个答案:

答案 0 :(得分:0)

以下是我解决的方法,如果有人知道更好的方法,请发回答案。

 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...',
    ));
    }