Setting error messages dynamically in Model Behaviors PDF Print E-mail
User Rating: / 0
PoorBest 
CakePHP - Basics
Written by Stuart Duncan   
Thursday, 12 November 2009 23:05

I decided to tackle my own file upload behavior in CakePHP for 2 reasons....  1, I want to learn this stuff so plugging in an already made script will only gain me so much knowledge, and 2, none of the scripts out there really do what I need, which is some interesting video functionality. Anyway, I quickly ran into a rather big road block which I could not find an answer too... not in other examples, not in other tutorials, not in books or even the CakePHP chat room. I figure it's probably partially because I can't explain myself quite clearly enough to get across what I want to do, but also because the solution is so incredibly simple that no one would ever think that they'd need to give that answer to you. It's just too easy!

Dynamic error messages from a Behavior, create them on the fly with variables....  easily!

Hopefully you've already read the Cookbook and grasped a few of the basics, particularly the $validate parameter of the Model class. It can get rather complicated and it can also be rather simple if you let it. Take the examples of the cookbook page and try it in action, it's not so bad.

One thing to mention which is a little more complicated but still easy enough is that you can specify method names in your validate rules, so that it will call that method and do some work and return true or false. I'll give you an example:

<?php
class Post extends AppModel {
var $validate = array(
'title' => array(
'rule' => 'checkLength',
'message' => 'The title is the incorrect length'
)
);

function checkLength(){
if( strlen($this->data['Post']['title'] > 30 ) return false;
if( strlen($this->data['Post']['title'] < 2 ) return false;
return true;
}
}

I don't even know if that's exactly right but you get the point. If the title's length is too short or too long, it returns false, it doesn't validate, it doesn't go into the database. Great stuff! PS, I know there is custom CakePHP validation methods that can do this for us, but bear with me, this is a quick example.

Ok, now that I have that out of the way, you can see how it calls a method and gets a response, I found myself writing this kind of thing up for my file upload behavior and getting frustrated quickly. Look at the example above. See how it returns false in 2 cases? What if you want it to specifically tell the user that it's too long... not just "wrong"?? What if you want it to say it's too short when it's too short??

This was my exact problem, hopefully this can help you too... at least in the learning stages. I'm sure there are better ways once you get far enough along with CakePHP but for now, let's learn some neat little things that no one ever told us.

I wanted a validate rule that would check the PHP file upload array for an error, get it's number and output a string stating what the problem is. You can find the errors and their meanings here: Error messages explained.

See how it has an error for file size, permissions, partial uploads?? Wouldn't it be handy to return that to the user?

My issue, for the longest time, was that I could have a validate rule point to a method, have the method check for that error and determine if the number is above 0, it should return false. But I could not figure out how to return a message specific to the number, much less a message that would tell the user what the max upload size is. That is until I just tried something totally on a whim, just for fun... and it worked.

This is what I did:

var $validate = array(
'filefield = array(
'rule' => 'fileError'
)
);

function fileError(){
switch( $this->data['filefield']['error'] ){
case 1:
return 'File size exceed. Please keep files under ' . ini_get('upload_max_filesize');
break;

case 2:
return 'File size exceed. Please keep files under ' . ini_get('upload_max_filesize');
break;

case 3:
return 'The uploaded file was only partially uploaded. Please try again.';
break;

case 4:
return 'No file was uploaded';
break;

case 6:
return 'Temp folder on server is not available.';
break;

case 7:
return 'Unable to write to disk.';
break;

default:
return true;
}
}

Notice that I don't have to tell it to return false? I wish someone would have told me that sooner... and that my friend, is the magic here. CakePHP knows to look for true as a response to validate and anything else is a fail.... but if it's not specifically a false, and a string instead, then to make that string the error message! So now, if someone uploads a file that is larger than what is in the PHP.ini file, it'll say so!!

Didn't I tell you that the solution was simple? It took me a while to figure this one and not because it's hard, but because I couldn't find any articles or answers anywhere that simple said, return the error message you idiot!

And this, I'm learning, is the secret to learning CakePHP... I have to essentially unlearn a lot of what I've learned. To give up my need for controlling every functionality, every outcome... to give up reasoning like expecting a true or false when I want a valid or invalid.

If you are trying to get better error messages than what you can set in a $validate array, just return it!

 

Add comment


Security code
Refresh

Login to TyCamTech.com

Donate

Must have Pepsi, feed my addiction here:


Recommended Books

Introduction to Programming
A Quick And Easy Ebook That Introduces Readers To Computer Programming In A Jargon Free, Easy To Understand Way.

How To Flip Websites Home Study Course.
Complete Video Instruction On How To Quickly Set And And Flip (i.e. Sell) Websites For Profit. 6 X Video Lessons Plus Bonuses -- Great Value For Buyer And Maximum 75% Payout For Affiliate!

Setting up a Web Server
Teaches All The Steps To Hosting A Website From Home.

Follow us on



Follow tycamtech on Twitter