Symfony: How to execute raw SQL which returns objects inside Form

Ever wanted to fetch your entities using complex query from inside you form class? Check out below.

All code was tested on Symfony 5, but after small changes (or even without) it should work also in Symfony 4.

So we’re starting with injecting Entity Manager to our form:

Next in buildForm method, just fetch required data (in our example we’re fetching from JSON type field):

And thats it. Beware that using ‘query_builder’ property as shown in Symfony doc, you need to return QueryBuilder object which makes it impossible to execute raw sql.

Leave a Reply