Nifty time-saving form / validation function for CodeIgniter

Note: This needs to be seriously tweaked to work better with more complex model functions.  I am leaving this up but understand that for now it only handles one-variable model functions easily.

I’m lazy when I code. By lazy I mean I detest retyping the same several codes of line multiple times throughout an app. My motto is (usually) if I have to use a/several line(s) more than 3 times it becomes a function so I can use and re-use it.

If you’re like me, when you use the form features in CI you set up the controller part like so:

if($this->validation->run() == FALSE) {
$data["variable"] = "something";
} else {
$process = $this->model_name->model_function($this->validation->variable);
//Success / error message here

That (extremely simple) example uses only 7 lines of code. However, if you have an add + edit function in each controller and you have 10 controllers, that’s (7+7)*10 = 140 lines that are really similar. I hear a function calling my name!

With the function I created I took those six lines of code and reduced them to this:

Pretty sweet, no? 🙂

Below is the function. I am assuming you have a basic to intermediate understanding of CI, so I won’t go into a lot of depth explaining it. I placed validation_run in the custom forms library I use. You can use it in your own custom library or create a library out of it. If you put it in your own library, ensure that the method you are using to reference CI functions is reflected in validation_run ($this->obj,$ci,$this->ci, etc). Also ensure that the Validation and Model are loaded prior to calling validation_run.

function validation($model_name,$model_function,$model_function_variable,$layout_template,$data_array=NULL)

if($this->ci->validation->run() == FALSE) {
//This allows the view to be called with or without parameters.
if(!is_null($data_array)) {
} else {
} else {
$process = $this->ci->$model_name->$model_function(
//Use your favorite redirection method here

To use it, you’d simply call


For better readability you could do alternatively do it this way:


Of course, you’d replace library_name with the library name you called it from.

Not everyone will have a use for this function; it’s really only good for simple validation “running” . However, it’s saved me so much time coding that I had to share it 🙂


Leave a comment

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: