The state of my MY_Model. Inserting data directly from forms with from_form() method

Well… it’s a mess, but it works good for now. And I think it’s evolving, one sign of this being the fact that 20 people stared it on the Github repository (

And now I’ve added a new method to it, namely from_form(), which, by using the form_validation library is taking the data to be inserted from the form.

This means that now you can at any time directly insert values from forms into the tables. First of all make sure you have a fillable or a protected property, because you must make sure no one interferes with your id’s or whatever you use to uniquely identify the rows.

After you’ve done this, you must set the rules. If you use the MY_Model’s form validation, I advise you to write the rules inside your model. Below you can find an example of model:



defined('BASEPATH') OR exit('No direct script access allowed');

class User_model extends MY_Model
  public $protected = array('id');

  function __construct()

  public $rules = array(
    'insert' => array(
    'username' => array('field'=>'username','label'=>'Username','rules'=>'trim|required'),
    'email' => array('field'=>'email','label'=>'Email','rules'=>'trim|valid_email|required')

After setting the model this way, you are ready to go. So, in your controller you can go like this (for the view to work, I am assuming you have loaded the form helper):

public function add_user()
  $id = $this->user_model->from_form()->insert();
  if($id === FALSE)
    echo $id;
    //...whatever you want to do. the form was submitted and the data was inserted

Also, the view should look like this:


echo form_open();
echo form_label('Username','username').':<br />';
echo form_error('username');
echo form_input('username',set_value('username')).'<br />';

echo form_label('Email','email').':<br />';
echo form_error('email');
echo form_input('email',set_value('email'));

echo form_submit('submit','Save user');
echo form_close();

MY_Model on its Github repository

Leave a Reply

Your email address will not be published. Required fields are marked *

No spam? * Time limit is exhausted. Please reload CAPTCHA.