Custom Error Handling in CakePHP when debug = 0

Not sure if this is the most correct way to handle this, but I wanted to use a custom error method in my controllers. However, if you’ve been working with CakePHP a bit, you’ll notice that Cake automatically throws a 404 error when you set debug to 0.

To get around this I opened up /cake/libs/error.php and commented out the following lines:

/*if (Configure::read() == 0) {
$method = 'error404';
if (isset($code) && $code == 500) {
$method = 'error500';
}
}*/

This seems to solve the problem, for now. Hopefully this will be fixed in a future version of Cake because I detest modifying core files.

Advertisements

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 😀