Symfony2:如何向FormBuilder添加一个Doctrine Entity数组 [英] Symfony2: how to add a Doctrine Entity Array to FormBuilder

查看:173
本文介绍了Symfony2:如何向FormBuilder添加一个Doctrine Entity数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与Symfony和Doctrine合作,我有一个功能可以根据具体条件选择行:

  $ entities = $ repository-> getSomeEntities(); 

现在我想将这些实体呈现在选择列表中,我查看了实体 FormType,但我无法实现我正在寻找的。

示例:




'class'=>'Path\To\Entity')(
'class'=&
'property'=>'id'
));

上述代码工作正常,除了它选择所有实体。



我检查了Symfony文档 http://symfony.com /doc/current/reference/forms/types/entity.html ,似乎实现这一点的唯一方法是使用不适用于我的情况的query_builder选项



有没有添加 $实体数组到我的表单作为选择列表?

解决方案

看到你实现 ChoiceListProvider Symfony 中有许多实现,但您可能需要简单的 SimpleChoiceListProvider


  1. 通过 EntityManager 实例来形成(通过构造函数或选项)

  2. 将表单字段定义为选择,而不是实体

  3. 设置其 choice_list to new MySimpleChoiceLIstProvider($ this-> entityManager)

您可以(可能会)将更多的东西传递给提供商,而不是仅仅将 EntityManager 传递给您,就像您所说的将根据特定条件选择行。如果这个标准来自表单本身,你应该可以通过 FormEvents 来实现,这将允许您访问数据对象。



希望这有帮助。


i'm working with Symfony and Doctrine, i have a function that will select rows based on specific criteria:

$entities = $repository->getSomeEntities();

now i want to render those entities in a choice list, i checked the entity FormType but i couldn't achieve what i'm looking for.

Example:

     $builder->add('id','entity', array(
        'class' => 'Path\To\Entity',
        'property' => 'id'
    ));

the above code works fine except it selects all the Entities.

i checked Symfony documentation http://symfony.com/doc/current/reference/forms/types/entity.html and it seems that the only way to achieve this is by using query_builder option which wont work for my case

Is there anyway to add the $entities array to my form as a choice list ?

解决方案

See that you implement ChoiceListProvider. There are many implementation built into Symfony but you might need something as simple as SimpleChoiceListProvider.

  1. Pass EntityManager instance to form (either via constructor or options)
  2. Define form field as choice, not entity
  3. Set its choice_list to new MySimpleChoiceLIstProvider($this->entityManager)

You could (probably will) pass something more than just EntityManager to provider as you said "will select rows based on specific criteria". If that criteria origins from form itself you should probably do it via FormEvents which will give you access to data object.

Hope this helps.

这篇关于Symfony2:如何向FormBuilder添加一个Doctrine Entity数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆