Symfony2: how to add a Doctrine Entity Array to FormBuilder

﹥>﹥吖頭↗ 提交于 2019-12-12 05:58:19

问题


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 ?


回答1:


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.




回答2:


With what you wrote, there are no reasons the QueryBuilder doesn't work.

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".

could you show us why it doesn't work ? Thank you



来源:https://stackoverflow.com/questions/20086151/symfony2-how-to-add-a-doctrine-entity-array-to-formbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!