| Limit pagination results per page and total number of results! |
|
|
|
| CakePHP - Basics | |||
| Written by Stuart Duncan | |||
| Wednesday, 03 February 2010 13:34 | |||
|
I spent many hours searching and asking in chat rooms and Cakephp's site and just banging my head against the desk on this one... how in the world do you limit a pagination queries results to x number per page and y number in total?? I wanted to display the top 1000 results out of 1850 or so that I had in the database and show 20 per page. It seems like a pretty simple problem on the surface but if you try it, you'll see how frustrating it can be. As I said, no one had an answer!! It wasn't until I stopped, sat down and had some lunch that it dawned on me... the simple problem, had a simple solution! I already had a 'paginateCount' method in my model's PHP file... if you hadn't read my earlier articles, I had a problem with my paginate returning proper 'has and belongs to many' relations so I had to create my own paginateCount method to return the proper number of results. Anyway, if I didn't already have one, I never would have solved this. Here's how it goes:
1: Make something up!My first step was to pass something to the paginate array that would make it recognize the number of results I wanted. I had read all the articles on all the available options, nothing did what I needed, so I made up something. Now my paginate variable looks like this:
Look it up, that 'totallimit' option doesn't exist. But for me, it does now!! 2: paginateCount() Custom MethodIn the model (in my case, entry.php), I added in a new custom method that would do all the counting of the pagination results, it also is what tells the pagination when to stop retrieving records from the database. The default look of it, and what you should start with is this:
This is what CakePHP needs before it will allow you to take over the counting of the results. In the previous article, it was used to handle some issues that it had with big table relations. This time, it'll reutrn our new limit. My new custom method now looks like this:
And that's it!! It's not hard to tell what it's doing... it merges the arrays into something that CakePHP will like (it likes arrays), and runs it through the database. Now, if there is a total limit set and it's lower than what was returned from the database, then return the total limit number. Otherwise return what the database says since it hasn't hit the limit. For example, my database has 1850 results. If I set 'totallimit' => 2000.... it would return a result of 1850 since that's all there is. But, if I set 'totallimit' => 1000, then it will return 1000 instead of 1850 because it's all I want. And there you have it. Limit your page count AND your total result count by making up variables.... and then using them! |





Comments
RSS feed for comments to this post.