2017-07-18 66 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