简体   繁体   English

Symfony2:如何将Doctrine实体数组添加到FormBuilder

[英]Symfony2: how to add a Doctrine Entity Array to FormBuilder

i'm working with Symfony and Doctrine, i have a function that will select rows based on specific criteria: 我正在使用Symfony和Doctrine,我有一个可以根据特定条件选择行的函数:

$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. 现在,我想在选择列表中呈现这些实体,我检查了entity FormType,但无法实现所需的功能。

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 我检查了Symfony文档http://symfony.com/doc/current/reference/forms/types/entity.html ,看来实现此目的的唯一方法是使用query_builder选项,该选项不适用于我的情况

Is there anyway to add the $entities array to my form as a choice list ? 无论如何,有没有将$entities数组作为选择列表添加到我的表单中?

See that you implement ChoiceListProvider . 看到您实现ChoiceListProvider There are many implementation built into Symfony but you might need something as simple as SimpleChoiceListProvider . Symfony内置了许多实现,但是您可能需要像SimpleChoiceListProvider这样简单的东西。

  1. Pass EntityManager instance to form (either via constructor or options) EntityManager实例传递给表单(通过构造函数或选项)
  2. Define form field as choice , not entity 将表单字段定义为choice而不是entity
  3. Set its choice_list to new MySimpleChoiceLIstProvider($this->entityManager) 将其choice_list设置为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". 您可以(可能将)不只是将EntityManager传递给提供程序,正如您所说的“将根据特定条件选择行”。 If that criteria origins from form itself you should probably do it via FormEvents which will give you access to data object. 如果该条件源自表单本身,则可能应该通过FormEvents ,这将使您可以访问数据对象。

Hope this helps. 希望这可以帮助。

With what you wrote, there are no reasons the QueryBuilder doesn't work. 使用您编写的内容,没有任何理由QueryBuilder无法正常工作。

You should have something like that : 你应该有这样的东西:

    $builder
            ->add('fieldname', 'entity', array(
                'class' => 'Path\to\Entity',
                'query_builder' => function(\Doctrine\ORM\EntityRepository $er) {
                                        return $er->yourFunction();
                                    },
                'required' => true
                ))

with "yourFunction" a function of your repository, for your example "getSomeEntities". 使用“ yourFunction”作为存储库的功能,例如“ getSomeEntities”。

could you show us why it doesn't work ? 您能告诉我们为什么它不起作用吗? Thank you 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM