I’ve allocated quite a reasonable amount of time to find a good bundle to achieve pagination AND use NativeQuery in the same time. I didn’t. Maybe I should have searched more…

Anyway, here it is in a nutshell, until I find some time to turn this into a bundle.

Goal: paginate records that are obtained both with NativeQuery and QueryBuilder in Doctrine.

What do we have:

  • entity called Process

What should we achieve at the end of this post:

  • one listing page with records resulted from a NativeQuery – paginated
  • one listing page with records resulted from QueryBuilder – paginated

First, let’s take care of Controller.

File/class called ProcessController should have an indexNativeAction where we will display a list of Process entities using NativeQuery. We’ll go for a simple approach:

Then, to fill all the gaps, we’ll continue with creating the Paginator custom class, needed for doing almost all the work. Go ahead and create a Paginator.php file somewhere (I prefer a “Lib” folder inside the bundle).

This class will contain the most important method : paginate() but also a bunch of getters for the class params like count of all records in query, current page #, how many pages are in total, etc.

Now, let’s build the result in Repository. We’re going to create method getProcessesNativeQuery() that returns the NativeQuery which will collect whatever we’re interested in. In this case : all the Process entities (you can be more creative):

I think we have all setup for the final step: view . This is where all takes shape.

Let’s create the actual listing page, indexNative.html.twig.

Let’s see how the template for one Process entity listing looks like:

And the pagination navigator:

All you need to do is setup the number of items per page (the “limit”) as parameter and all this should work just fine. We’ll set it to 10 by adding it in paramaters.yml file

At this point, you have everything working with NativeQuery.

What about QueryBuilder?

Basically it’s all the same, except one thing: repository should return a QueryBuilder (instead of NativeQuery).

For that, create a new method in repository called getProcessesQueryBuilder(), like this:

After that, of course you need to adjust the controller to call this for getting the results. Change the controller as follows:


This should be enough for you application to handle pagination for both NativeQueries and DQL in Doctrine.

Need help with your next project?

Contact us

Privacy Preference Center