Welcome Guest, Not a member yet? Register   Sign In
Model and Form
#9

In most cases, I keep my validation rules in the model and have a method in the base model (get_validation_rules()) to return the validation rules. Then my controller can do the following:




PHP Code:
$this->form_validation->set_rules($this->some_model->get_validation_rules());

// Add more rules if necessary

// Validate
if ($this->form_validation->run() === false) { 
 
   return false;
}

// Since the data is valid, 
// give it to the model
$data $this->some_model->prep_data($this->input->post());

if (
$insert) {
 
   $result $this->some_model->insert($data);
} else {
 
   $result $this->some_model->update($data);
}

// do whatever else needs 
// to be done before returning 

Since the method to get the validation rules (and prep, insert, and update the data) is in the base model, I have the flexibility to choose when and where I use them without writing a bunch of boiler-plate code for each model. Some models might need a heavier controller to handle odd circumstances, while others might not need much more code than what I've included above (or could even trim that down by handling the decision to insert/update in the model).

I have a handful of odd models to do things like read data from an array (maybe pulled from a file, or even stored in a property in the model) which still use the same methods used in the base model for data access. This allows me to move the data to the database later, if needed, without changing my controller(s) and/or view(s). In many cases, I can do it by just changing the base class of my model or removing the custom (overriding) methods from the model.
Reply


Messages In This Thread
Model and Form - by aurelien - 11-20-2014, 03:24 AM
RE: Model and Form - by Rufnex - 11-20-2014, 04:10 AM
RE: Model and Form - by ivantcholakov - 11-20-2014, 05:00 AM
RE: Model and Form - by bclinton - 11-20-2014, 07:59 AM
RE: Model and Form - by slax0r - 11-20-2014, 04:11 PM
RE: Model and Form - by RobertSF - 11-20-2014, 05:59 PM
RE: Model and Form - by bclinton - 11-20-2014, 07:26 PM
RE: Model and Form - by slax0r - 11-21-2014, 01:43 AM
RE: Model and Form - by bclinton - 12-12-2014, 04:58 PM
RE: Model and Form - by mwhitney - 12-12-2014, 03:21 PM
RE: Model and Form - by bclinton - 12-12-2014, 04:55 PM
RE: Model and Form - by mwhitney - 12-15-2014, 10:02 AM
RE: Model and Form - by jaynarayan - 12-18-2015, 10:44 AM



Theme © iAndrew 2016 - Forum software by © MyBB