Codeigniter and Jquery Easyui CRUD

thumbnail

Hi Guys, welcome back to codingofcents.com. Today we will discuss how to make simple CRUD(Create Update Delete) with Codeigniter framework dan Jquery EasyUI.

CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.

Jquery EasyUI is a complete framework for the HTML5 web page. It provides easy to use components for building modern, interactive, javascript applications that work on pc and mobile devices.

Codeigniter use MVC (Model View Controller) pattern, therefore make us easily to maintain the code.

Before starting this tutorial makes sure you download both Codeigniter dan Jquery Easyui on their official website.

After download, extract the compressed files and move Codeigniter files to the server root. For the Jquery Easyui file put at application root and create a new folder name it assets.

Codeigniter and Jquery Easyui file structure
Codeigniter and Jquery Easyui file structure

Configuration

First open config Codeigniter file in application/config/config.php, this file use for setting our application. We will override the default setting to make the automatic switch to Http or https (if you have SSL). And also make the URL SEO friendly, so it’s like http://host/action not like http://host/index.php/action. To archive, update config file so like bellow

$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$base_url .= "://". @$_SERVER['HTTP_HOST'];
$base_url .=     str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = $base_url;


/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';

Then, update database file in application/config/database.php change hostname, username, password, and database to your machine configuration

'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'db_ci_easyui',

Then on application/config/routes.php change default controller to your controller

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

View

First, let us create view for displaying our application, create a file at applications/views folder. I’ll name it welcome_message.php and code bellow. As you can see, we also add script files for our frontend logic. Create a javascript file at assets/js folder, I’ll name it script.js.

In the view, we create a container that wraps the application. In container we create a Datagrid table, dialog, and toolbar. Datagrid is a component that displays data in table format.

Datagrid have a toolbar for the navigation, each of they has onclick event for show dialog (create and update) and delete row.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>CodeIgniter with JQuery Easyui</title>
    <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/easyui/themes/metro/easyui.css') ?>">
    <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/easyui/themes/icon.css') ?>">
    <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/css/bootstrap.min.css') ?>">
    <script type="text/javascript" src="<?php echo base_url('assets/easyui/jquery.min.js') ?>"></script>
    <script type="text/javascript" src="<?php echo base_url('assets/easyui/jquery.easyui.min.js') ?>"></script>
    <script type="text/javascript" src="<?php echo base_url('assets/js/script.js') ?>"></script>
</head>
<body>

<div id="container" class="easyui-layout" fit="true">
    <div region="center">
        <table id="dgCustomers" toolbar="#toolbarCustomer" class="easyui-datagrid" fit="true" singleSelect="true" fitColumns="true" rowNumbers="false" pagination="true" url="<?= site_url('welcome/getcustomers') ?>" pageSize="50" pageList="[25,50,75,100,125,150,200]" nowrap="false">
            <thead>
                <tr>
                    <th field="customerNumber" width="80">Customer Number</th>
                    <th field="customerName" width="100">Name</th>
                    <th field="contactFirstName" width="100">Contact First Name</th>
                    <th field="contactLastName" width="100">Contact Last Name</th>
                    <th field="phone" width="50">Phone</th>
                    <th field="addressLine1" width="100">First Address</th>
                    <th field="addressLine2" width="100">Second Address</th>
                    <th field="city" width="50">City</th>
                    <th field="state" width="50">State</th>
                    <th field="postalCode" width="50">Postal Code</th>
                    <th field="country" width="50">Country</th>
                </tr>
            </thead>
        </table>
        <div id="toolbarCustomer">
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onClick="newCustomer()">New</a>
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onClick="editCustomer()">Edit</a>
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onClick="destroyCustomer()">Destroy</a>
            <input  id="searchCustomer" class="easyui-searchbox" data-options="prompt:'Please Input Value',searcher:doSearchCustomer,
            inputEvents: $.extend({}, $.fn.searchbox.defaults.inputEvents, {
                keyup: function(e){
                    var t = $(e.data.target);
                    var opts = t.searchbox('options');
                    t.searchbox('setValue', $(this).val());
                    opts.searcher.call(t[0],t.searchbox('getValue'),t.searchbox('getName'));
                }
              })" style="width:50%;"></input>
        </div>
    </div>

    <div id="dlgCustomer" class="easyui-dialog" style="width: 780px; height: auto; padding: 10px;" modal="true" closed="true" buttons="#dlgCustomerBtn">
        <form id="fmCustomer" method="post">
            <div class="col-sm-12 justify-content-sm-center">
                <div class="row" style="width: 100%">
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label for="">Customer Name</label>
                            <input type="text" name="customerName" class="easyui-textbox" style="width: 100%;">
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label for="">Contact First Name</label>
                            <input type="text" name="contactFirstName" class="easyui-textbox" style="width: 100%;"></div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label for="">Contract Last Name</label>
                            <input type="text" name="contactLastName" class="easyui-textbox" style="width: 100%;"></div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label for="">Phone</label>
                            <input type="text" name="phone" class="easyui-textbox" style="width: 100%;"></div>
                    </div>
                </div>
                <div class="row" style="width: 100%">
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label for="">First Address Line</label>
                            <input type="text" name="addressLine1" multiline="true" class="easyui-textbox" style="width: 100%;">
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label for="">Second Address Line</label>
                            <input type="text" name="addressLine2" multiline="true" class="easyui-textbox" style="width: 100%;"></div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label for="">City</label>
                            <input type="text" name="city" class="easyui-textbox" style="width: 100%;"></div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label for="">State</label>
                            <input type="text" name="state" class="easyui-textbox" style="width: 100%;"></div>
                    </div>
                </div>
                <div class="row" style="width: 100%">
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label for="">Postal Code</label>
                            <input type="text" name="postalCode" class="easyui-textbox" style="width: 100%;">
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label for="">Country</label>
                            <input type="text" name="country" class="easyui-textbox" style="width: 100%;"></div>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <div id="dlgCustomerBtn">
        <a href="javascript:void(0)" id="btn_save" class="easyui-linkbutton" iconCls="icon-ok-a" onclick="saveCustomer()" style="width:90px">Save</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-del-a" onclick="javascript:$('#dlgCustomer').dialog('close'); $('#fmEmployee').form(clear)
        " style="width:90px">Cancel</a>
    </div>
</div>

</body>
</html>

And here our script like

var ttl;
function doSearchCustomer(){
	$('#dgCustomers').datagrid('load',{
		search_customer: $('#searchCustomer').val()
	});
}

function newCustomer() {
	$('#dlgCustomer').dialog('open').dialog('setTitle','Add Vendor Contacts');
	$('#fmCustomer').form('clear');
	url = 'Welcome/saveCustomer';
	ttl = "new";
}

Jquery Easyui uses JSON for its data in Datagrid, so we need to create a Controller that handles that request and model that get data from the database.

Create a controller at the application/controllers folder and name it Welcome. In the Welcome controller first, we need to load the model then create an index method to display our view.

Method getCustomers() used for return data JSON from model.

<?php 

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

class Welcome extends CI_Controller {
	public function __construct()
	{
		parent::__construct();
		$this->load->model(['model_customers']);
	}
	public function index()
	{
		$this->load->view('welcome_message');
	}
	public function getCustomers()
	{
		$this->output->set_content_type('application/json');
		$employee = $this->model_customers->getCustomers();
		echo json_encode($employee);
	}
}

Create a model file at applications/models folder and name it Model_customer. In the model, we first load database drivers at the construct method. Then get customers() method is used to get data from database.

<?php 

class Model_customers extends CI_Model
{
	
	function __construct()
	{
		parent::__construct();
		$this->load->database();
	}

	public function getCustomers()
	{
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 50;
        $sort = isset($_POST['sort']) ? strval($_POST['sort']) : 'customers.customerNumber';
        $order = isset($_POST['order']) ? strval($_POST['order']) : 'asc';
        $search = isset($_POST['search_customer']) ? strval($_POST['search_customer']) : '';
        $offset = ($page-1)*$rows;

        $result = array();
        $result['total'] = $this->db->get('customers')->num_rows();
        $row = array();

        // select data from table product
        $query = "SELECT *
            from customers
            where concat(customerName,'',contactLastName,'',contactFirstName)  
            like '%$search%' order by $sort $order limit $offset, $rows";

        $country = $this->db->query($query)->result_array();    
        $result = array_merge($result, ['rows' => $country]);
        return $result;
	}

}

Create

After we create a method for display data then we mush create method for store the data to the database.

First, in the Welcome controller add saveCustomer method. This method call saveCustomer method from the model.

public function saveCustomer()
{
	$input = $this->model_customers->saveCustomer();
	if ($input) {
		echo json_encode(['success' => true]);
	}else {
		echo json_encode(['Msg'=>'Some Error occured!.']);
	}
}

In model_customer add saveCustomer method to store data from the database. This method return id of saved row.

public function saveCustomer()
{
    $data = [
        'customerName' => $this->input->post('customerName'),
        'contactFirstName' => $this->input->post('contactFirstName'),
        'contactLastName' => $this->input->post('contactLastName'),
        'phone' => $this->input->post('phone'),
        'addressLine1' => $this->input->post('addressLine1'),
        'addressLine2' => $this->input->post('addressLine2'),
        'city' => $this->input->post('city'),
        'state' => $this->input->post('state'),
        'postalCode' => $this->input->post('postalCode'),
        'country' => $this->input->post('country'),
    ];
    
    $this->db->insert('customers',$data);
    return $this->db->insert_id();
}

In script file add saveCustomer function to send a post request to the controller. In the view you can see we add onclick event that calls saveCustomer function.

saveCustomer function will validate the form before submitted


function saveCustomer() {
	$('#fmCustomer').form('submit',{
		url: url,
		onSubmit: function(){
			return $(this).form('validate');
		},
		success: function(result){
			var result = eval('(' + result + ')');
			if (result.errorMsg){
				$.messager.show({
					title: 'Error',
					msg: result.errorMsg
				});
			} else if (result.success){
                $('#dlgCustomer').dialog('close');		// close the dialog
				$('#dgCustomers').datagrid('reload');	// reload the user data
                $('#fmCustomer').form('clear');
                var opts = $('#dgCustomers').datagrid('getColumnFields', true);
                var msg = ttl == "updt" ? "Update data success" : "New data added successfully";
                var title = ttl == "updt" ? "Data Update" : "New data";
                $.messager.alert({
                    title: title,
                    msg: msg,
                    fadeOut: 'slow',
                    showType:'fade',
                });
            }else {
				 $.messager.alert({
                    title: 'Error',
                    msg: "Encourage Error!"
                });
			}
		}
	});
}

Update

To update data first we need to add some function id script. We name it editCustomer. This function will get data from selected Datagrid and fill the form with selected data. If the user press update button it will call saveCustomer function as we create before.

function editCustomer() {
	var row = $('#dgCustomers').datagrid('getSelected');
	if (row){
		$('#dlgCustomer').dialog('open').dialog('setTitle','Edit');
		$('#fmCustomer').form('load',row);
		url = 'Welcome/updateCustomer/'+row.customerNumber;
		ttl = "updt";
	}else {
		$.messager.alert('Warning','Contact not selected!');
	}
}

In controller add updateCustomer method that has id params from request. This method calls updateCustomer method form model.

public function updateCustomer($id)
{
	$input = $this->model_customers->updateCustomer($id);
	if ($input) {
		echo json_encode(['success' => true]);
	}else {
		echo json_encode(['Msg'=>'Some Error occured!.']);
	}
}

In model create updateCustomer method for update data in database.

public function updateCustomer($id)
{
    $data =  [
        'customerName' => $this->input->post('customerName'),
        'contactFirstName' => $this->input->post('contactFirstName'),
        'contactLastName' => $this->input->post('contactLastName'),
        'phone' => $this->input->post('phone'),
        'addressLine1' => $this->input->post('addressLine1'),
        'addressLine2' => $this->input->post('addressLine2'),
        'city' => $this->input->post('city'),
        'state' => $this->input->post('state'),
        'postalCode' => $this->input->post('postalCode'),
        'country' => $this->input->post('country')
    ];

    $this->db->where('customerNumber',$id);
    $this->db->set($data);
    return $this->db->update('customers');
}

Delete

Add destroyCustomer function in the script that uses for send requests to the controller.

function destroyCustomer() {
	var row = $('#dgCustomers').datagrid('getSelected');
	if (row){
		$.messager.confirm('Confirm','Are you sure you want to delete this Vendor..? All data under this Vendor will be disappear',function(r){
			if (r){
				$.post('Welcome/destroyCustomer',{id:row.customerNumber},function(result){
					if (result.success){
						$('#dgCustomers').datagrid('reload');	// reload the Vendor data
					} else {
						$.messager.show({	// show error message
							title: 'Error',
							msg: result.errorMsg
						});
					}
				},'json');
			}
		});
	}
}

In customer add destroyCustomer method, this method gets id params from request and call destroyCustomer method in the model.

public function destroyCustomer()
{
	$id = intval($_REQUEST['id']);
	$input = $this->model_customers->destroyCustomer($id);
	if ($input) {
		echo json_encode(array('success'=>true));
	}else {
		echo json_encode(array('errorMsg'=>'Some errors occured.'));
	}
}

And finally, add destroyCustomer method in the model for delete data from the database.

public function destroyCustomer($id)
{
    $this->db->where('customerNumber',$id);
    return $this->db->delete('customers');
    // return $this->db->delete($this->table,['id' => $id]);
}

For source code, you can find at https://github.com/Tisna/Codeigniter-and-easyui/

Sponsored Links
Hi, my name is I Wayan Tisna Adi Muliarta. You can call me Tisna. I am the author of the Coding Of Cents

Leave a Reply

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

four × three =

Back To Top