Quick Little Tip Regarding Cakephp forms

Occasionally when I am coding something in Cake that requires a form, I run into a problem if I use something like

if( !empty($this->data) ) ...

If there is another method that posts to the URL that the above code rests on (an Auth class trying to preserve the page the person was trying to reach, for example), then chances are good the method will think the user is trying to post to that method as well.

Anyway, my quick solution to ensure that only the data *I* want is posted is this:

if( !empty($this->data['ModelName']) ) { ..

This ensures that the method is only looking for the data that we want to post to it.

Advertisements

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.

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 😀