问题
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.
- Pass
EntityManagerinstance to form (either via constructor or options) - Define form field as
choice, notentity - Set its
choice_listtonew 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