簡體   English   中英

Symfony 3 Form EntityType字段不包含空選項

[英]Symfony 3 Form EntityType field does not take empty choices

當$ this-> getChoices()返回一個空數組時,以下代碼將繼續加載。

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

我知道一種解決方案是在選項為空時使用ChoiceType更改EntityType 但是,想知道對此問題有任何更好的修復。

以下是我解決的方法,如果有人知道這樣做的更好方法,請發表您的答案。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM