2017-07-18 69 views
0

我想用數組填充我的ChoiceType,但它看起來像是用ID填充而不是用值填充。表單被正確顯示,但選項是'0','1'...而不是數組中的名稱。Symfony用數組填充ChoiceType

這是我的控制器:

$categories = $this->getDoctrine()->getRepository('myBundle:Category')->findAll(); 

    $techChoices = array(); 
    $i = 0; 
    foreach($categories as $t) { 
     $techChoices[$i] = $t->getName(); 
     $i = $i + 1; 
    } 

    $formOptions = array('categories' => $techChoices); 


    $document = new Document($categories); 
    $form = $this->createForm(DocumentType::class, $document, $formOptions); 

這是我buildForm:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('file', FileType::class) 
     ->add('file_name', TextType::class) 
     ->add('file_description', TextType::class) 
     ->add('file_group', ChoiceType::class, array(
      'choices' => $options['categories'], 
     )); 
} 

public function configureOptions(OptionsResolver $resolver) 
{ 
    $resolver->setDefaults(array(
     'categories' => array(), 
    )); 
} 

回答

0

如果你想直接在形式選擇類型使用數組,然後看到https://symfony.com/doc/current/reference/forms/types/choice.html#example-usage,或者如果你想從一個表(實體)使用的數據,然後看https://symfony.com/doc/current/reference/forms/types/entity.html#basic-usage

回答你的問題是數組格式應該像

[ 'data_to_be_seen1'=> VALUE1(ID), 'data_to_be_seen2'=> VALUE2(ID),...]

(參見第一鏈路),

所有最好的

+0

非常感謝,第二個鏈接正是我所需要的。它現在有效 – LordArt

0

你可以直接做到這一點:

$builder 
    ->add('file', FileType::class) 
    ->add('file_name', TextType::class) 
    ->add('file_description', TextType::class) 
    ->add('file_group', ChoiceType::class, array(
     'choices' => 'here you pass your categories entities directly', 
     'choice_label' => 'name', 
    )); 

這樣的,它會做的映射獨自一人

+0

你是什麼意思的「在這裏你直接傳遞你的類別實體」?我試着用數組 – LordArt

+0

爲什麼你重新創建一個數組?只是通過findAll結果 –

+1

我這樣做是因爲我試圖按照答案給某個具有相同問題的人,但是當我通過findAll結果時,它是一樣的 – LordArt

1

取決於Symfony的版本(自2.8開始),您正在以錯誤的方式構建選擇數組。

3.3 documentation

...其中數組關鍵是項目的標籤和數組值是項目的價值。

+0

我正在像'選擇'例子那樣做, m只是試圖傳遞一個現有的數組,而不是聲明一個新的。 – LordArt

0

正確的方式來顯示您的案例中的類別是使用EntityType,這將釋放你的代碼混亂。您不必再獲取/傳遞類別。

public function buildForm(FormBuilderInterface $builder, array $options) { 
     $builder 
       ->add('file', FileType::class) 
       ->add('file_name', TextType::class) 
       ->add('file_description', TextType::class) 
       ->add('file_group', \Symfony\Bridge\Doctrine\Form\Type\EntityType::class, array(
        // query choices from this entity 
        'class' => 'AppBundle:Category', 
        'choice_label' => 'name', 
       )) 

     ; 
    } 
+0

這就是我所做的,就像@abhinand說的,謝謝 – LordArt