The technique stated on Step 4 and Step 5 works well if data is loaded from a single DB table. But if data requires more difficult loading and saving, it's better to create a separate model class.
As an example, let's create a model object for the grid we built on Step 4.
We will divide the step into 3 substeps:
In our model we will specify functions for:
"models/event_model.php" file
<?php
class Event_model extends CI_Model {
var $event_name;
var $start_date;
var $end_date;
function __construct()
{
parent::__construct();
}
//returns an array with data
function get($request){
$query = $this->db->get("events");
return $query->result_array();
}
//the function takes values of the row data
protected function get_values($action){
$this->event_name = $action->get_value("event_name");
$this->start_date = $action->get_value("start_date");
$this->end_date = $action->get_value("end_date");
}
//inserts a new event
function insert($action){
$this->get_values($action);
if ($this->validate($action)){
$this->db->insert("events", $this);
$action->success($this->db->insert_id());
}
}
//updates an event
function update($action){
$this->get_values($action);
if ($this->validate($action)){
$this->db->update(
"events",
$this,
array("event_id" => $action->get_id())
);
$action->success();
}
}
// validates an event before saving
function validate($action){
if ($this->event_name == ""){
$action->invalid();
$action->set_response_attribute(
"details",
"Empty text is not allowed"
);
return false;
}
return true;
}
//deletes an event
function delete($action){
$this->db->delete("events", array("event_id" => $action->get_id()));
$action->success();
}
}
?>
We won't create a new view and will use the view file specified on Step 4.
And let's create a new controller that will process our model.
The difference between the current controler and the controller file of the Step 4 lies is 2 commands:
$this->load->model("event_model");// loads the model
$connector->useModel($this->event_model);//applies the model
The commands allows us to load our model and apply it in the project.
"controllers/gridmodel.php" file
require_once("./dhtmlx/connector/grid_connector.php");
require_once("./dhtmlx/connector/db_phpci.php");
DataProcessor::$action_param ="dhx_editor_status";
class GridModel extends CI_Controller {
public function index()
{
//grid's view
$this->load->view('grid');
}
public function data()
{
//data feed
$this->load->database();
$this->load->model("event_model");
$connector = new GridConnector($this->db, "PHPCI");
$connector->configure(
"events",
"event_id",
"start_date, end_date, event_name"
);
$connector->useModel($this->event_model);
$connector->render();
}
}