Symfony2:如何向FormBuilder添加一个Doctrine Entity数组 [英] Symfony2: how to add a Doctrine Entity Array to FormBuilder
问题描述
我正在与Symfony和Doctrine合作,我有一个功能可以根据具体条件选择行:
$ entities = $ repository-> getSomeEntities();
现在我想将这些实体呈现在选择列表中,我查看了实体
FormType,但我无法实现我正在寻找的。 p>
示例:
(
'class'=>'Path\To\Entity')(
'class'=&
'property'=>'id'
));
上述代码工作正常,除了它选择所有实体。
我检查了Symfony文档 http://symfony.com /doc/current/reference/forms/types/entity.html ,似乎实现这一点的唯一方法是使用不适用于我的情况的query_builder选项
有没有添加 $实体
数组到我的表单作为选择列表?
看到你实现 ChoiceListProvider
。 Symfony
中有许多实现,但您可能需要简单的 SimpleChoiceListProvider
。
- 通过
EntityManager
实例来形成(通过构造函数或选项) - 将表单字段定义为
选择
,而不是实体
- 设置其
choice_list
tonew 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
.
- Pass
EntityManager
instance to form (either via constructor or options) - Define form field as
choice
, notentity
- Set its
choice_list
tonew 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屋!