问题
I'm using the entity Field Type in a Symfony2.1 form. Here, I'm going to use the query_builder
param to return only entities that matches a long-complex query (see the example in the official docs).
Obviously the query_builder
param for the entity field type accepts a Doctrine QueryBuilder object. On the other side, I have large entity repositories with complex DQL queries obtained by the EntityManager's createQuery()
function which returns a Doctrine Query object.
So, I cannot directly use all these queries in the entity field type. Moreover, rewriting all the queries for the use with a QueryBuilder would be a non-sense.
Is there such a way to automatically translate from the Query object to the QueryBuilder object?
回答1:
From Symfony2 docs:
query_builder - type:
Doctrine\ORM\QueryBuilder
or aClosure
<---If specified, this is used to query the subset of options (and their order) that should be used for the field. The value of this option can either be a
QueryBuilder
object or aClosure
. If using aClosure
, it should take a single argument, which is theEntityRepository
of the entity.
Now, I haven't got time to try an example but it seems to me that if you use Closure
you could return ArrayCollection
(or at least array
) of target entity objects. Your Closure
gets object of EntityRepository
as an argument so there's no need to rewrite all that stuff.
Mind giving it a shot? :)
UPDATE
... sorry for kept you waiting...
It seems that it's not possible this way. Instead you would have to use choice
form type and feed entity objects (or objects repository as I did) manually.
I've made some simplified example here: http://ideone.com/LHdi2E
Hope this helps...
来源:https://stackoverflow.com/questions/13285281/from-doctrine-query-to-querybuilder-in-a-simfony2-entity-field-type