Quick 'n' Easy Way to Dynamically Set Per Page Limits with CakePHP's pagination

Maybe this is old news to some Cake veterans, but it took me longer than I would’ve liked to figure this out.

I have a settings table which holds a “per_page” variable and value, to allow admins to set their own per page limits for their site. However, because Cake defines $paginate variable like so:
public $paginate = array(..);
you cannot define a Configure::read or $variable to pass the “limit” key along. And pasting $this->paginate in 4 or 5 actions was not my idea of a good time.

After some head-scratching it dawned on me – define the other keys (fields, order, etc) in the $paginate variable and then simply define the “limit” key in the action itself!

Now here’s what my Controllers look like:
public $paginate = array(
'ModelName' => array(
'order' => ..,
'fields' => ..,
"conditions" => ..
)
);

Then in my action, I simply do a quick check to see if the per page limit has been set (don’t want to limit 0,0!!), and if so, set that as the limit variable:
if( $limit = Configure::read("per_page") AND !empty($limit) ) {
$this->paginate["ModelName"]["limit"] = $limit;
}

I couldn’t believe how easy it was 😀

Advertisements
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: