I will teach you how to implement the jqGrid plugin with codeigniter.

 

 

What is jqGrid?

Jqgrid is one of the cool jquery grid plugin available for FREE!. The grid is a Ajax-enabled JavaScript control that provides solution for representing tabular data on the web. Since the grid is client-side solution and loading data dynamically through Ajax callbacks, it can be integrated with any server side technology.

What you need?

  • jQuery 1.4 or higher (Download)
  • latest version of the jqGrid plugin (Download)
  • Latest version of CodeIgniter (Download)
  • You need the css from Jquery UI for styling (Download)
  • The PHP jqgrid library and the grid helper file (Download)
Now that were all set, lets move FORWARD!!!

Load the css
1
2
<link rel="stylesheet" type="text/css" href="/css/ui.jqgrid.css" />
<link type="text/css" rel="stylesheet" href="/css/jquery-ui-1.8.12.custom.css" />
Load the javascript files
1
2
3
<script type="text/javascript" src="/js/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="/js/jqgrid/grid.locale-en.js"></script>
<script type="text/javascript" src="/js/jqgrid/jquery.jqGrid.src.js"></script>

Load the jqgrid helper

you can also auto-load the helper in your /application/config/autoload.php, but here I will load the helper manually

1
2
$this->load->helper('grid_helper');
$this->load->helper('url_helper');

Initialize Grid Parameters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
$aData = array(
'set_columns' => array(
array(
'label' => 'Customer ID',
'name' => 'custid',
'width' => 100,
'size' => 10
),
array(
'label' => 'Customer Name',
'name' => 'custname',
'width' => 220,
'size' => 10
),
array(
'label' => 'Status',
'name' => 'custstatus',
'width' => 100,
'size' => 10
)
),
'div_name' => 'grid',
'source' => 'customer/customerList/',
'sort_name' => 'custname',
'add_url' => 'customer/exec/add',
'edit_url' => 'customer/exec/edit',
'delete_url' => 'customer/exec/del',
'caption' => 'Customer Maintenance',
'primary_key' => 'custid',
'grid_height' => 230
);

OK, So the I’ll explain the parameters

  • set_columns: these are the column for your grid (You can add more column options by editing grid_helper.php).
  • div_name: div id where the jqgrid would be rendered.
  • source: The url parameter where the data would be fetched (I will tell you the contents of /customer/customerlist/ later).
  • sort_name: The column name that is sorted by default.
  • delete_url, add_url, edit_url: is the the jquery would redirect when editing,adding or deleting a record.
  • caption: Caption in the grid’s title bar.
  • primary_key: The primary key in your grid, this key would be passed when you are editing or deleting a record when the appropriate action button is pressed.
  • grid_height: set the height of the grid.
Back to the source parameter, we need to build a function in your controller where the data would be fetched. In my example I used /customer/customerlist/. Here is the source code of my customerlist.
1
2
3
4
5
6
7
8
buildGridData(
array(
'model' => 'customer_model',
'method' => 'getAllCustomers',
'pkid' => 'custid',
'columns' => array( 'custid','custname','custstatus' )
)
);

I used the function from grid_helper.php called buildGridData, you just need to specify the model name, the model’s method, the primary id of the returned field and the columns that would be fetched.In the method of the model here is the snippet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function getAllCustomers($paramArr) {
$start = isset($paramArr['start'])?$paramArr['start']:NULL;
$limit = isset($paramArr['limit'])?$paramArr['start']:NULL;
$sortField = isset($paramArr['sortField'])?$paramArr['sortField']:'custname';
$sortOrder = isset($paramArr['sortOrder'])?$paramArr['sortOrder']:'asc';
$whereParam = isset($paramArr['whereParam'])?$paramArr['whereParam']:NULL;
if(!empty($start) && !empty($limit)) $optLimit = "limit $start,$limit";
else $optLimit = NULL;

if(!empty($whereParam)) $whereParam = "and (".$whereParam.")";
$whereClause = "where true ".$whereParam;

$SQL = "SELECT * FROM tblcustomer $whereClause order by $sortField $sortOrder $optLimit ";
$result = $this->db->query($SQL);

if($result->num_rows() > 0) {
$custlist = $result->result();
return $custlist;
} else {
return null;
}
}

Now its time to build the grid and load it to your view file:

1
2
$data['customerGrid'] = buildGrid($aData);
$this->load->view( 'customer/customerlist',$data );

We just need to pass the built array and load it to your view file, you just need to echo the customerGrid in your view. Don’t FORGET to add a table with id=”grid” and a div with id=”pager” (jqgrid needs a placeholder)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JqGrid Demo</title>
<link rel="stylesheet" type="text/css" href="/css/ui.jqgrid.css" />
<link type="text/css" rel="stylesheet" href="/css/jquery-ui-1.8.12.custom.css" />
<script type="text/javascript" src="/js/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui-1.8.12.custom.min.js"></script>
<script type="text/javascript" src="/js/jqgrid/grid.locale-en.js"></script>
<script type="text/javascript" src="/js/jqgrid/jquery.jqGrid.src.js"></script>
</head>
<body>
<table id="grid"></table>
<div id="pager"></div>
<?php echo $customerGrid; ?>
</body>
</html>

OK now were finished!

For the sake of the people that cannot download the zip,

here is the code for the library and the helper

Heres the code for the library:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
<?php
/*@Developer - Mark Lenard M. Mirandilla
*@Version 1.0
*@Description jqgrid library for Codeigniter
*/

class JqGrid {
private $divName;
private $sourceUrl;
private $colNames;
private $colModels;
private $sortName;
private $caption;
private $gridHeight;
private $addUrl;
private $editUrl;
private $deleteUrl;
private $customButtons;
private $customFunctions;
private $subgrid;
private $subGridUrl;
private $subGridColumnNames;
private $subGridColumnWidth;

public function setColumns($columns) {
$tmpColNames = array();
$tmpColModels = '';

foreach ($columns as $columnNames => $columnOptions) {
foreach ($columnOptions as $columnName => $columnOption) {
$tmpColNames[] = $columnName;
$tmpColModels .= json_encode($columnOption).",";
}
}
$this->colNames = json_encode($tmpColNames);
$this->colModels = '['.$tmpColModels.']';
}

public function setDivName($divName) {
$this->divName = $divName;
}

public function setSourceUrl($url) {
$this->sourceUrl = $url;
}

public function setSortName($sortName) {
$this->sortName = $sortName;
}

public function setCaption($caption) {
$this->caption = $caption;
}

public function setGridHeight($height) {
$this->gridHeight = $height;
}

public function setPrimaryKey($primaryKey) {
$this->primaryKey = $primaryKey;
}

public function setAddUrl($url) {
$this->addUrl = $url;
}

public function setEditUrl($url) {
$this->editUrl = $url;
}

public function setDeleteUrl($url) {
$this->deleteUrl = $url;
}

public function setCustomButtons($buttons) {
$this->customButtons = $buttons;
}

public function setCustomFunctions($customFunctions) {
$this->customFunctions = $customFunctions;
}

public function setSubGrid($isSubGrid = FALSE) {
$this->subGrid = $isSubGrid;
}

public function setSubGridUrl($subGridUrl) {
$this->subGridUrl = $subGridUrl;
}

public function setSubGridColumnNames($columnNames) {
$this->subGridColumnNames = $columnNames;
}

public function setSubGridColumnWidth($columnWidth) {
$this->subGridColumnWidth = $columnWidth;
}

public function buildGrid() {
$buildDivName = $this->divName;
$buildSourceUrl = $this->sourceUrl;
$buildColNames = $this->colNames;
$buildColModels = $this->colModels;
$buildSortName = $this->sortName;
$buildEditUrl = $this->editUrl;
$buildAddUrl = $this->addUrl;
$buildDeleteUrl = $this->deleteUrl;
$buildCaption = $this->caption;
$buildGridHeight = $this->gridHeight;
$buildPrimaryKey = $this->primaryKey;
$buildCustomButtons = $this->customButtons;
$buildSubGrid = $this->subgrid;
$buildSubGridUrl = $this->subGridUrl;
$buildSubGridColumnNames = $this->subGridColumnNames;
$buildSubGridColumnWidth = $this->subGridColumnWidth;

$grid = "<script type='text/javascript'>";
$grid .= "$('#$buildDivName').jqGrid({
url:'$buildSourceUrl',
datatype: 'json',
colNames:$buildColNames,
colModel:$buildColModels,
rowNum:20,
rowList:[10,20,30],
pager: '#pager',
toppager:true,
cloneToTop:true,
sortname: '$buildSortName',
viewrecords: true,
sortorder: 'asc',
caption:'$buildCaption'"
;
$grid .= "});";

//NavBar
$grid .= "$('#$buildDivName').jqGrid('navGrid','#pager',
{search:true,edit:false,add:false,del:false,cloneToTop:true}, //options
{} // search options
)"
;
if( !empty( $buildCustomButtons ) ){
foreach($buildCustomButtons as $customButton) {
$customButton = ".navButtonAdd('#grid_toppager_left',".$customButton.")";
$grid .= $customButton;
}
}

$grid .= ".navButtonAdd('#grid_toppager_left',
{ caption:'', buttonicon:'ui-icon-trash', onClickButton:jqGridDelete ,title: 'Delete selected row', position: 'first', cursor: 'pointer'})
.navButtonAdd('#grid_toppager_left',
{ caption:'', buttonicon:'ui-icon-pencil', onClickButton:jqGridEdit,title: 'Edit selected row', position: 'first', cursor: 'pointer'})
.navButtonAdd('#grid_toppager_left',
{ caption:'', buttonicon:'ui-icon-plus', onClickButton:jqGridAdd,title: 'Add new record', position: 'first', cursor: 'pointer'});"
;

$grid .= "
function jqGridAdd() {
location.href='$buildAddUrl?oper=add';
}

function jqGridEdit() {
var grid = $('#$buildDivName');
var sel_id = grid.jqGrid('getGridParam', 'selrow');
var myCellData = grid.jqGrid('getCell', sel_id, '$buildPrimaryKey');
if(!myCellData) {
alert('No selected row');
} else {
//alert(myCellData);

location.href='$buildEditUrl' + myCellData;
}
}

function jqGridDelete() {
var grid = $('#$buildDivName');
var sel_id = grid.jqGrid('getGridParam', 'selrow');
var recid = grid.jqGrid('getCell', sel_id, '$buildPrimaryKey');
if(!recid) {
alert('No selected row');
} else {
var ans = confirm('Delete selected record?');
if(ans) {
var data = {};
data.recid = recid;
$.post('$buildDeleteUrl',data);
$('#$buildDivName').trigger('reloadGrid');
}
}
}

"
;
if( !empty( $this->customFunctions ) ){
foreach($this->customFunctions as $customFunction) {
$grid .= $customFunction;
}
}

//Set Grid Height
$grid .= "$('#$buildDivName').setGridHeight($buildGridHeight,true);";
$grid .= "$('.ui-jqgrid-titlebar-close','#gview_$buildDivName').remove();";
$grid .= "</script>";
return $grid;
}
}

and heres the code for the helper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
<?php
function buildGrid( $aData ){
$CI =& get_instance();
$CI->load->library('JqGrid');
$jqGrid = $CI->jqgrid;
if( isset( $aData['set_columns'] ) ){
$aProperty = array();
foreach( $aData['set_columns'] as $sProperty ){
$aProperty[] = array(
$sProperty['label'] =>
array(
'name' => $sProperty['name'],
'index' => $sProperty['name'],
'width' => $sProperty['width'],
'editable' => false,
'editoptions' => array(
'readonly'=>'true',
'size'=> $sProperty['size']
)
)
);
}
$jqGrid->setColumns( $aProperty );
}

if( isset( $aData['custom'] ) ){
if( isset( $aData['custom']['button'] ) ){
$jqGrid->setCustomButtons( array( $aData['custom']['button'] ) );
}
if( isset( $aData['custom']['function'] ) ){
$jqGrid->setCustomFunctions( array( $aData['custom']['function'] ) );
}
}

if( isset( $aData['div_name'] ) ){
$jqGrid->setDivName( $aData['div_name'] );
} else {
$jqGrid->setDivName( 'grid' );
}

if( isset( $aData['source'] ) ) $jqGrid->setSourceUrl( base_url() . $aData['source'] );

if( isset( $aData['sort_name'] ) ) $jqGrid->setSortName( $aData['sort_name'] );

if( isset( $aData['add_url'] ) ) $jqGrid->setAddUrl( base_url() . $aData['add_url'] );

if( isset( $aData['delete_url'] ) ) $jqGrid->setDeleteUrl( base_url() . $aData['delete_url'] );

if( isset( $aData['edit_url'] ) ) $jqGrid->setEditUrl( base_url() . $aData['edit_url'] );

if( isset( $aData['caption'] ) ) $jqGrid->setCaption( $aData['caption'] );

if( isset( $aData['primary_key'] ) ) $jqGrid->setPrimaryKey( $aData['primary_key'] );

if( isset( $aData['grid_height'] ) ) $jqGrid->setGridHeight( $aData['grid_height'] );

if( isset( $aData['subgrid'] ) ) $jqGrid->setSubGrid($aData['subgrid']);

if( isset( $aData['subgrid_url'] ) ) $jqGrid->setSubGridUrl($aData['subgrid_url']);

if( isset( $aData['subgrid_columnnames'] ) ) $jqGrid->setSubGridColumnNames($aData['subgrid_columnnames']);

if( isset( $aData['subgrid_columnwidth'] ) ) $jqGrid->subGridColumnWidth($aData['subgrid_columnwidth']);

return $jqGrid->buildGrid();
}

function buildGridData( $aData ){
$CI =& get_instance();

$isSearch = $CI->input->get('_search');
$searchField = $CI->input->get('searchField');
$searchString = $CI->input->get('searchString');
$searchOperator = $CI->input->get('searchOper');
$page = $CI->input->get('page'); // get the requested page
$limit = $CI->input->get('rows'); // get how many rows we want to have into the grid
$sidx = $CI->input->get('sidx'); // get index row - i.e. user click to sort
$sord = $CI->input->get('sord'); // get the direction

if($isSearch) $whereParam = buildWhereClauseForSearch($searchField,$searchString,$searchOperator);
else $whereParam = NULL;

$paramArr['whereParam'] = $whereParam;
$paramArr['reload'] = TRUE;
/*
you can add aditional params in the where clause here:
$paramArr['outletid'] = $CI->session->userdata(SELECTED_OUTLET);
$paramArr['invtypeId'] = $CI->session->userdata(SELECTED_INVENTORY_TYPE);
$paramArr['postingYear'] = getPostingYear();
*/

if( isset( $aData['method'] ) && isset( $aData['model'] ) ){
$CI->load->model( $aData['model'] );
$aDataList = $CI->$aData['model']->$aData['method']($paramArr);
$count = count($aDataList);
if( $count >0 ) $total_pages = ceil($count/$limit);
else $total_pages = 0;

if ($page > $total_pages) $page=$total_pages;
$start = $limit*$page - $limit;

$paramArr['start'] = $start;
$paramArr['limit'] = $limit;
$paramArr['sortField'] = $sidx;
$paramArr['sortOrder'] = $sord;
$paramArr['whereParam'] = $whereParam;
$paramArr['reload'] = TRUE;
$aDataList = $CI->$aData['model']->$aData['method']($paramArr);

$i=0;
if( isset( $aData['columns'] ) ){
foreach ($aDataList as $row)
{
$columnData = array();
foreach( $aData['columns'] as $sData ){
array_push( $columnData, $row->$sData );
}
$rs->rows[$i]['id'] = $row->$aData['pkid'];
$rs->rows[$i]['cell'] = $columnData ;
$i++;
}
}
$rs->cols = $columnData;
$rs->page = $page;
$rs->total = $total_pages;
$rs->records = $count;
echo json_encode($rs);
}

function buildWhereClauseForSearch($searchField,$searchString,$searchOperator) {
$searchString = mysql_real_escape_string($searchString);
$searchField = mysql_real_escape_string($searchField);
$operator['eq'] = "$searchField='$searchString'"; //equal to
$operator['ne'] = "$searchField<>'$searchString'"; //not equal to
$operator['lt'] = "$searchField < $searchString"; //less than
$operator['le'] = "$searchField <= $searchString "; //less than or equal to
$operator['gt'] = "$searchField > $searchString"; //less than
$operator['ge'] = "$searchField >= $searchString "; //less than or equal to
$operator['bw'] = "$searchField like '$searchString%'"; //begins with
$operator['bn'] = "$searchField not like '$searchString%'"; //not begins with
$operator['in'] = "$searchField in ($searchString)"; //in
$operator['ni'] = "$searchField not in ($searchString)"; //not in
$operator['ew'] = "$searchField like '%$searchString'"; //ends with
$operator['en'] = "$searchField not like '%$searchString%'"; //not ends with
$operator['cn'] = "$searchField like '%$searchString%'"; //in
$operator['nc'] = "$searchField not like '%$searchString%'"; //not in
$operator['nu'] = "$searchField is null"; //is null
$operator['nn'] = "$searchField is not null"; //is not null

if(isset($operator[$searchOperator])) {
return $operator[$searchOperator];
} else {
return null;
}
}
}

Note: I just wanted to share to you guys the codeigniter library that I developed and used from my previous project. Of course you can customize it to meet your requirements. Please give me some feedback or suggestion on how to improve this library. Thanks for using my library. Next Version is for sub-grid and adding custom buttons per cell row.

Tags: , , , , , , , , , , , , ,

Categories: Codeigniter ,Javascript ,Jquery ,PHP


86 Responses to “How to implement Triand’s JqGrid with Codeigniter”

  1. Chris says:

    Great job Mark! Layout and design looks cool and simple. Also, cool tuts there ;)

  2. Mario says:

    help please, i can’t download your library and helper, the site is down…

  3. Marcone says:

    Hi. I can’t download your library too… :(

  4. kugutsumen says:

    Hi folks I have pasted the code from both the library and the helper hope this helps. Please share to me your updates on bug fixes and/or enhancements
    thanks for your support guys!

  5. Ryan says:

    Thanks for your help with jqGrid & CI, however, with your code I’m getting an error with my system trying to load the ‘common_helper’ (in your helper file under the function buildGridData). Is this something I need to additionally download and install?
    Thanks again!

    • admin says:

      Hi Ryan,
      I updated the post, I should have removed the inclusion of common helper, it should work with out the common helper, let me know if I can help you more. Thanks! hope to get a feedback from you soon! :-)

      • Ryan says:

        Thanks for that. I removed the line on my file and now I can’t seem to get the code to work at all. I get a vague server error message.

  6. CJ says:

    I’m glad I found this tutorial today. I haven’t got it working yet, but it isn’t giving any error messages either. Since you know your code and the logic behind it, would it be possible for you to put in some ‘log_message(‘error’,'XXX’)’ instances at key points within the code? It would help out with troubleshooting tremendously.
    Thanks for putting this together!

  7. kugutsumen says:

    Hi guys I will retest again my code probably later today, and see to it that it works flawlessly.
    thanks!

  8. Ryan says:

    Forgot to autoload the URL helper class!

  9. kugutsumen says:

    Ok Guys I updated the tutorial specifically the view where the grid is being echoed. We need to add
    a table with id=”grid” and a div with id=”pager” to have a placeholder for the grid to be rendered.
    Hope this helps!
    Let me know guys if you still encounter a problem.
    Coming up this weekend is a downloadable working demo for this…

    • Marcone says:

      Hi! First, thank you for sharing this, you got very good tutorials here. I still didn’t get the helper to work. I’m not sure if I am doing anything wrong. The table columns loads but empty. I checked the controller function that fetches the data and I got one error at line 95 of grid_helper.php. I fixed it. The problem was that $limit value was 0. It doesn’t show errors anymore, but still doesn’t work. Could that be my model method?
      function getAllTextsForTable(){
      $this->db->order_by(“id”, “asc”);
      $query=$this->db->get(“text”);
      return $query->result();
      }
      or could it be a jquery issue?
      (Sorry for the english)

  10. kugutsumen says:

    heres my implementation in the model method

    function getAllCustomers($paramArr) {
          $start = isset($paramArr['start'])?$paramArr['start']:NULL;
          $limit = isset($paramArr['limit'])?$paramArr['start']:NULL;
          $sortField = isset($paramArr['sortField'])?$paramArr['sortField']:'custname';
          $sortOrder = isset($paramArr['sortOrder'])?$paramArr['sortOrder']:'asc';
          $whereParam = isset($paramArr['whereParam'])?$paramArr['whereParam']:NULL;
          $reload = isset($paramArr['reload'])?$paramArr['reload']:FALSE;
    
          if(!$reload) {
             $cachedCustomerList = get_cache(CACHE_CUSTOMERLIST);
             if($cachedCustomerList) return $cachedCustomerList;
          }
    
          if(!empty($start) && !empty($limit)) $optLimit = "limit $start,$limit";
          else $optLimit = NULL;
    
          if(!empty($whereParam)) $whereParam = "and (".$whereParam.")";
          $whereClause = "where true ".$whereParam;
    
          $SQL = "SELECT * FROM tblcustomer $whereClause order by $sortField $sortOrder $optLimit ";
          $result = $this->db->query($SQL);
    
          if($result->num_rows() > 0) {
             $custlist = $result->result();
             set_cache(CACHE_CUSTOMERLIST,$custlist);
             return $custlist;
          } else {
             return null;
          }
       }
    
  11. kugutsumen says:

    @Ryan @Marcone Im glad that I’ve help you guys… feel free to share this library to others :-D

    • kugutsumen says:

      btw, I finaly made a working and downloadable demo
      heres the link:
      Working demo
      Download demo

      • Kino says:

        Hi Mister,

        I cannot download this zip, it stops at 28 % , haven’t you got another location?

        Thanks

        • Chinna says:

          I downloaded and your demo and tried out. Its working. Thanks for sharing. I would like to customize the navigation button. Can you please help me how to customize the button from the controller. like ‘set_actions’ => array(
          “add”=>false, // allow/disallow add
          “edit”=>false, // allow/disallow edit
          “delete”=>true, // allow/disallow delete
          “rowactions”=>true, // show/hide row wise edit/del/save option
          “export”=>true, // show/hide export to excel option
          “autofilter” => true, // show/hide autofilter for search
          “search” => “simple” // show single/multi field search condition (e.g. simple or advance)
          )

          Thanks

  12. Chris says:

    Hey – just tried out your demo and got it working..
    How do you make the cells available for inline editing?
    Thanks!

    • kugutsumen says:

      Hi Chris, Actually I haven’t made the cell work for inline editing yet, but I’ll let you know in a couple of weeks until I finish version 2 of this library, this would include, subgrids and inline editing…
      thanks,
      mark

    • ken says:

      Exactly what did you do to get this running.
      I followed the following steps and I see the grid, but no data…
      1. I downloaded the demo and extracted into its own directory.
      2. I created a database and imported the data given in the folder.
      3. Updated config/database.php to point to local database.
      4. Updated config/config.php with base url.
      5. Had to update 1 line in supplier controller as the grid helper file was named jqgrid in the download.

      Have I missed something here???

  13. Anders says:

    Hi,

    thanks for this, I got it working after some trial and error after trying the demo and modifying it for my purposes. Found an error in the downloadable demo though:

    $data['supplierGrid'] = buildGrid($aData);

    In the view the data variable is $grid. It took me a while to find this, but after changing that it worked! Just thought you might want to know! Thanks again.

    Anders

      • Anders says:

        I have another question, though:

        I want the default sort order to be ‘desc’ on a particular field. The sort order you set by the parameters don’t seem to help (read somewhere that they only have to do with the button for changing the sort order). Anyway, on the JqGrid site I found that the parameter to set is firstsortorder. But how would I implement this in your helper for CodeIgniter?

        Thanks, /Anders

        • Anders says:

          Actually, two questions, if you don’t mind :-)

          The second one is: I need to be able to process parts of the results before presenting it in the grid, like one field I need to parse the string of that field in each record (a uri that I’m extracting the search string from). Is there any way to do this before passing it to the grid? So for example, in your downloadable example $supplierList is returned from the method in the model. Can I somehow process that return variable (I don’t even know what type it is…) and parse the string in this field for each record, and then pass it to the grid?

          /Anders

        • kugutsumen says:

          Hi sanders, heres how I would implement the setting of the sort order,

          in the jqgrid_lib.php, line 47 you’ll find a function named setSortName, here is the updated function

          1
          2
          3
          4
          5
              public function setSortName($sortName,$sortOrder) {
                  $this->sortName = $sortName;
                  if($sortOrder === 'desc' || $sortOrder === 'asc') $this->sortOrder = $sortOrder;
                  else $sortOrder === 'asc';
              }

          In the jqgrid_helper.php line 43,

          1
          if( isset( $aData['sort_name'] ) ) $jqGrid->setSortName( $aData['sort_name'], $aData['sort_order']);

          after modifying the lib and helper you can now use

          ‘sort_order’ => ‘desc’,

          when passing array in buildGrid()
          e.g.

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          32
          33
          $aData = array(
                      'set_columns' => array(
                                           array(
                                              'label'  => 'Supplier ID',
                                              'name'   => 'supid',
                                              'width'  => 100,
                                              'size'   => 10
                                           ),
                                           array(
                                              'label'  => 'Supplier Name',
                                              'name'   => 'supname',
                                              'width'  => 220,
                                              'size'   => 10
                                           ),
                                           array(
                                              'label'  => 'Supplier Address',
                                              'name'   => 'supnadd',
                                              'width'  => 220,
                                              'size'   => 10
                                           )
                      ),
                      'div_name'     => 'grid',
                      'source'       => 'supplier/supplierList/',
                      'sort_name'    => 'supname',
                      'sort_order'   => 'desc',
                      'add_url'      => 'supplier/index/',
                      'edit_url'     => 'supplier/index/',
                      'delete_url'   => 'supplier/exec/del',
                      'caption'      => 'Supplier Maintenance',
                      'primary_key'  => 'supid',
                      'grid_height'  => 230
                );
                $data['supplierGrid'] = buildGrid($aData);
          • kugutsumen says:

            In your 2nd question,

            the type of the result from the db is an array of objects
            where the objects are your records

            here is a sample print_r of the result from the model

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            Array
            (
                [0] => stdClass Object
                    (
                        [supid] => 000005
                        [supname] => PT. PINDO DELI PULP AND PAPER MILLS
                        [supadd] => JAKARTA, INDONESIA
                        [supcontact_name] => TANTY YUNITA
                        [supmobileno] =>
                        [suplandlineno] =>  6221-3929-266 TO 69
                        [supfax] =>
                    )

                [1] => stdClass Object
                    (
                        [supid] => 000006
                        [supname] => SCOTT LO
                        [supadd] => TAIWAN
                        [supcontact_name] =>
                        [supmobileno] =>
                        [suplandlineno] =>
                        [supfax] =>
                    )
            )

            in that way. inside the method of your model, in my demo (getAllSuppliers method)
            you can use foreach in the result set,

            e.g. My goal is to concatinate (string)”TEST” in the suppliers name.

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
              $SQL = "SELECT supid, supname, supadd, supcontact_name, supmobileno, suplandlineno, supfax FROM tblsupplier";
                  $result = $this->db->query($SQL);
                  if($result->num_rows() > 0) {
                     $supplierList = $result->result();
                    }
                   
                    $newSupplierList = array();
                    foreach($supplierList as $supplier) {
                        $supplier->supname .= " TEST";
                        $newSupplierList[] = $supplier;
                    }
                    return $newSupplierList;

            hope this answers both of your question, I havent tested it yet, but I guess you can catch my idea on the implementation

            thanks,
            Mark

          • kugutsumen says:

            additional code for your question number 1,

            in jqgrid_lib.php add the ff

            line 118

            1
            $buildSortOrder = $this->sortOrder;

            and on line 133,

            1
            sortorder: '$buildSortOrder',

            let me know if my solution doesnt work, so I could provide you another solution tom.

            thanks,
            Mark

      • Prem says:

        Hello sir,
        I am a new user of codeigniter and wanna use jqgrid in it. I have download the upper file which you tagged but when i had tried it then didn’t got any output. just a blank screen is appear. I checked step by step but after $data['supplierGrid'] = buildGrid($aData); this in supplier page. i couldn’t move further.

  14. Anders says:

    Hi Mark,

    Thanks so much for helping out. Unfortunately, no I could not get the solution for question no 1 to work. I added the final two lines you mentioned as well, but it didn’t help…

    As for question no 2, that helped great! I just have a little follow-up question out of curiosity: I’m a newbie at both CodeIgniter and php, so maybe this should be obvious, but I was wondering how this part works:

    $newSupplierList[] = $supplier;

    I don’t get that. I can see it works, but to me that looks like it means the newSupplierList array is set to be the value of the current row each time in the loop, meaning that the value of the array is reset over and over? Apparently it doesn’t, since it works. But could you briefly explain why?

    Thanks!

    • kugutsumen says:

      Hi Anders,

      I’ll try out another solution later this day and send you a better solution for question number 1, for your followup question regarding the array I there is a php manual for that look at this php documentation
      http://php.net/manual/en/function.array-push.php

      thanks,
      Mark

      • Anders says:

        Thanks for pointing me to that part of the manual, good to know! /Anders

      • Anders says:

        Hi Mark!

        Did you get a chance to try out another solution for ordering the records as described above?

        Regards,

        Anders

        • kugutsumen says:

          Hi Anders,

          sorry for the late reply,,

          heres how I would implement a firstsortorder,

          in the helper file,
          add this in line 10

          1
          2
          3
          4
          5
          6
          7
          8
          9
          if(isset($sProperty['firstsortorder'])) {
                          if($sProperty['firstsortorder'] === 'asc' || $sProperty['firstsortorder'] === 'desc') {
                             $firstsortorder = $sProperty['firstsortorder'];
                          } else {
                              $firstsortorder = 'asc';
                          }
                      } else {
                          $firstsortorder = 'asc';
                      }

          and add this on line 15,

          1
          'firstsortorder'=>$firstsortorder,

          in your controller,
          when you set the columns and call the build grid function…
          set the forstsortorder

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          $aData = array(
                      'set_columns' => array(
                                           array(
                                              'label'  => 'Supplier ID',
                                              'name'   => 'supid',
                                              'width'  => 100,
                                              'size'   => 10
                                           ),
                                           array(
                                              'label'  => 'Supplier Name',
                                              'name'   => 'supname',
                                              'firstsortorder' => 'desc',
                                              'width'  => 220,
                                              'size'   => 10
                                           ),
                                           array(
                                              'label'  => 'Supplier Address',
                                              'name'   => 'supnadd',
                                              'width'  => 220,
                                              'size'   => 10
                                           )
                      ),

          btw with regards to delete,
          it does reload the grid upon delete, e.g. if you are in page 3, and deletes a records there, it reloads the page 3

          hope this helps,
          Mark

  15. Shankar says:

    Hi Kungutsumen,

    First of all hats off for this tutorial, i browsed a lot for something like this, but i think only your implimentation is simple and it works …. I faced a small problem while implementing two jqgrids in a single page. The pager was not displayed as expected, so i further extended the library and the helper by adding a pager variable, i can successfully see the grid controls of top pager and bottom pager, but only can see the Search and Refresh buttons, the rest of the buttons Add, Edit, Delete are not visible, can you help me out…will post the code of the library and helper below..

  16. Shankar says:

    Heres the helper

    load->library(‘JqGrid’);
    $jqGrid = $CI->jqgrid;
    if( isset( $aData['set_columns'] ) ){
    $aProperty = array();
    foreach( $aData['set_columns'] as $sProperty ){
    $aProperty[] = array(
    $sProperty['label'] =>
    array(
    ‘name’ => $sProperty['name'],
    ‘index’ => $sProperty['name'],
    ‘width’ => $sProperty['width'],
    ‘editable’ => false,
    ‘editoptions’ => array(
    ‘readonly’=>’true’,
    ‘size’=> $sProperty['size']
    )
    )
    );
    }
    $jqGrid->setColumns( $aProperty );
    }

    if( isset( $aData['custom'] ) ){
    if( isset( $aData['custom']['button'] ) ){
    $jqGrid->setCustomButtons( array( $aData['custom']['button'] ) );
    }
    if( isset( $aData['custom']['function'] ) ){
    $jqGrid->setCustomFunctions( array( $aData['custom']['function'] ) );
    }
    }

    if( isset( $aData['div_name'] ) ){
    $jqGrid->setDivName( $aData['div_name'] );
    } else {
    $jqGrid->setDivName( ‘grid’ );
    }

    if( isset( $aData['source'] ) ) $jqGrid->setSourceUrl( base_url() . $aData['source'] );
    if( isset( $aData['pager'] ) ) $jqGrid->setPager( $aData['pager'] );
    if( isset( $aData['sort_name'] ) ) $jqGrid->setSortName( $aData['sort_name'] );
    if( isset( $aData['add_url'] ) ) $jqGrid->setAddUrl( base_url() . $aData['add_url'] );
    if( isset( $aData['delete_url'] ) ) $jqGrid->setDeleteUrl( base_url() . $aData['delete_url'] );
    if( isset( $aData['edit_url'] ) ) $jqGrid->setEditUrl( base_url() . $aData['edit_url'] );
    if( isset( $aData['caption'] ) ) $jqGrid->setCaption( $aData['caption'] );
    if( isset( $aData['primary_key'] ) ) $jqGrid->setPrimaryKey( $aData['primary_key'] );
    if( isset( $aData['grid_height'] ) ) $jqGrid->setGridHeight( $aData['grid_height'] );
    if( isset( $aData['subgrid'] ) ) $jqGrid->setSubGrid($aData['subgrid']);
    if( isset( $aData['subgrid_url'] ) ) $jqGrid->setSubGridUrl($aData['subgrid_url']);
    if( isset( $aData['subgrid_columnnames'] ) ) $jqGrid->setSubGridColumnNames($aData['subgrid_columnnames']);
    if( isset( $aData['subgrid_columnwidth'] ) ) $jqGrid->subGridColumnWidth($aData['subgrid_columnwidth']);

    return $jqGrid->buildGrid();
    }

    function buildGridData( $aData ){
    $CI =& get_instance();

    $isSearch = $CI->input->get(‘_search’);
    $searchField = $CI->input->get(‘searchField’);
    $searchString = $CI->input->get(‘searchString’);
    $searchOperator = $CI->input->get(‘searchOper’);
    $page = $CI->input->get(‘page’); // get the requested page
    $limit = $CI->input->get(‘rows’); // get how many rows we want to have into the grid
    $sidx = $CI->input->get(‘sidx’); // get index row – i.e. user click to sort
    $sord = $CI->input->get(‘sord’); // get the direction

    if($isSearch) $whereParam = buildWhereClauseForSearch($searchField,$searchString,$searchOperator);
    else $whereParam = NULL;

    $paramArr['whereParam'] = $whereParam;
    $paramArr['reload'] = TRUE;
    /*
    you can add aditional params in the where clause here:
    $paramArr['outletid'] = $CI->session->userdata(SELECTED_OUTLET);
    $paramArr['invtypeId'] = $CI->session->userdata(SELECTED_INVENTORY_TYPE);
    $paramArr['postingYear'] = getPostingYear();
    */
    if( isset( $aData['method'] ) && isset( $aData['model'] ) ){
    $CI->load->model( $aData['model'] );
    $aDataList = $CI->$aData['model']->$aData['method']($paramArr);
    $count = count($aDataList);
    if( $count >0 ) $total_pages = ceil($count/$limit);
    else $total_pages = 0;

    if ($page > $total_pages) $page=$total_pages;
    $start = $limit*$page – $limit;

    $paramArr['start'] = $start;
    $paramArr['limit'] = $limit;
    $paramArr['sortField'] = $sidx;
    $paramArr['sortOrder'] = $sord;
    $paramArr['whereParam'] = $whereParam;
    $paramArr['reload'] = TRUE;
    $aDataList = $CI->$aData['model']->$aData['method']($paramArr);

    $i=0;
    if( isset( $aData['columns'] ) ){
    foreach ($aDataList as $row)
    {
    $columnData = array();
    foreach( $aData['columns'] as $sData ){
    array_push( $columnData, $row->$sData );
    }
    $rs->rows[$i]['id'] = $row->$aData['pkid'];
    $rs->rows[$i]['cell'] = $columnData ;
    $i++;
    }
    }
    $rs->cols = $columnData;
    $rs->page = $page;
    $rs->total = $total_pages;
    $rs->records = $count;
    echo json_encode($rs);
    }
    }

    function buildWhereClauseForSearch($searchField,$searchString,$searchOperator) {
    $searchString = mysql_real_escape_string($searchString);
    $searchField = mysql_real_escape_string($searchField);
    $operator['eq'] = “$searchField=’$searchString’”; //equal to
    $operator['ne'] = “$searchField’$searchString’”; //not equal to
    $operator['lt'] = “$searchField < $searchString"; //less than
    $operator['le'] = "$searchField $searchString”; //less than
    $operator['ge'] = “$searchField >= $searchString “; //less than or equal to
    $operator['bw'] = “$searchField like ‘$searchString%’”; //begins with
    $operator['bn'] = “$searchField not like ‘$searchString%’”; //not begins with
    $operator['in'] = “$searchField in ($searchString)”; //in
    $operator['ni'] = “$searchField not in ($searchString)”; //not in
    $operator['ew'] = “$searchField like ‘%$searchString’”; //ends with
    $operator['en'] = “$searchField not like ‘%$searchString%’”; //not ends with
    $operator['cn'] = “$searchField like ‘%$searchString%’”; //in
    $operator['nc'] = “$searchField not like ‘%$searchString%’”; //not in
    $operator['nu'] = “$searchField is null”; //is null
    $operator['nn'] = “$searchField is not null”; //is not null

    if(isset($operator[$searchOperator])) {
    return $operator[$searchOperator];
    } else {
    return null;
    }
    }

    The library

    $columnOptions) {
    foreach ($columnOptions as $columnName => $columnOption) {
    $tmpColNames[] = $columnName;
    $tmpColModels .= json_encode($columnOption).”,”;
    }
    }
    $this->colNames = json_encode($tmpColNames);
    $this->colModels = ‘['.$tmpColModels.']‘;
    }

    public function setDivName($divName) {
    $this->divName = $divName;
    }

    public function setSourceUrl($url) {
    $this->sourceUrl = $url;
    }

    public function setPager($pager){
    $this->pager = $pager;
    }

    public function setSortName($sortName) {
    $this->sortName = $sortName;
    }

    public function setCaption($caption) {
    $this->caption = $caption;
    }

    public function setGridHeight($height) {
    $this->gridHeight = $height;
    }

    public function setPrimaryKey($primaryKey) {
    $this->primaryKey = $primaryKey;
    }

    public function setAddUrl($url) {
    $this->addUrl = $url;
    }

    public function setEditUrl($url) {
    $this->editUrl = $url;
    }

    public function setDeleteUrl($url) {
    $this->deleteUrl = $url;
    }

    public function setCustomButtons($buttons) {
    $this->customButtons = $buttons;
    }

    public function setCustomFunctions($customFunctions) {
    $this->customFunctions = $customFunctions;
    }

    public function setSubGrid($isSubGrid = FALSE) {
    $this->subGrid = $isSubGrid;
    }

    public function setSubGridUrl($subGridUrl) {
    $this->subGridUrl = $subGridUrl;
    }

    public function setSubGridColumnNames($columnNames) {
    $this->subGridColumnNames = $columnNames;
    }

    public function setSubGridColumnWidth($columnWidth) {
    $this->subGridColumnWidth = $columnWidth;
    }

    public function buildGrid() {
    $buildDivName = $this->divName;
    $buildSourceUrl = $this->sourceUrl;
    $pager = $this->pager;
    $buildColNames = $this->colNames;
    $buildColModels = $this->colModels;
    $buildSortName = $this->sortName;
    $buildEditUrl = $this->editUrl;
    $buildAddUrl = $this->addUrl;
    $buildDeleteUrl = $this->deleteUrl;
    $buildCaption = $this->caption;
    $buildGridHeight = $this->gridHeight;
    $buildPrimaryKey = $this->primaryKey;
    $buildCustomButtons = $this->customButtons;
    $buildSubGrid = $this->subgrid;
    $buildSubGridUrl = $this->subGridUrl;
    $buildSubGridColumnNames = $this->subGridColumnNames;
    $buildSubGridColumnWidth = $this->subGridColumnWidth;

    $grid = “”;
    $grid .= “$(‘#$buildDivName’).jqGrid({
    url:’$buildSourceUrl’,
    datatype: ‘json’,
    colNames:$buildColNames,
    colModel:$buildColModels,
    rowNum:20,
    rowList:[10,20,30],
    pager: ‘#$pager’,
    toppager:true,
    cloneToTop:true,
    sortname: ‘$buildSortName’,
    viewrecords: true,
    sortorder: ‘asc’,
    caption:’$buildCaption’”;
    $grid .= “});”;

    //NavBar
    $grid .= “$(‘#$buildDivName’).jqGrid(‘navGrid’,'#$pager’,
    {search:true,edit:false,add:false,del:false,cloneToTop:true}, //options
    {} // search options
    )”;
    if( !empty( $buildCustomButtons ) ){
    foreach($buildCustomButtons as $customButton) {
    $customButton = “.navButtonAdd(‘#grid_toppager_left’,”.$customButton.”)”;
    $grid .= $customButton;
    }
    }

    $grid .= “.navButtonAdd(‘#grid_toppager_left’,
    { caption:”, buttonicon:’ui-icon-trash’, onClickButton:jqGridDelete ,title: ‘Delete selected row’, position: ‘first’, cursor: ‘pointer’})
    .navButtonAdd(‘#grid_toppager_left’,
    { caption:”, buttonicon:’ui-icon-pencil’, onClickButton:jqGridEdit,title: ‘Edit selected row’, position: ‘first’, cursor: ‘pointer’})
    .navButtonAdd(‘#grid_toppager_left’,
    { caption:”, buttonicon:’ui-icon-plus’, onClickButton:jqGridAdd,title: ‘Add new record’, position: ‘first’, cursor: ‘pointer’});”;

    $grid .= ”
    function jqGridAdd() {
    location.href=’$buildAddUrl?oper=add’;
    }

    function jqGridEdit() {
    var grid = $(‘#$buildDivName’);
    var sel_id = grid.jqGrid(‘getGridParam’, ‘selrow’);
    var myCellData = grid.jqGrid(‘getCell’, sel_id, ‘$buildPrimaryKey’);
    if(!myCellData) {
    alert(‘No selected row’);
    } else {
    //alert(myCellData);

    location.href=’$buildEditUrl’ + myCellData;
    }
    }

    function jqGridDelete() {
    var grid = $(‘#$buildDivName’);
    var sel_id = grid.jqGrid(‘getGridParam’, ‘selrow’);
    var recid = grid.jqGrid(‘getCell’, sel_id, ‘$buildPrimaryKey’);
    if(!recid) {
    alert(‘No selected row’);
    } else {
    var ans = confirm(‘Delete selected record?’);
    if(ans) {
    var data = {};
    data.recid = recid;
    $.post(‘$buildDeleteUrl’,data);
    $(‘#$buildDivName’).trigger(‘reloadGrid’);
    }
    }
    }

    “;
    if( !empty( $this->customFunctions ) ){
    foreach($this->customFunctions as $customFunction) {
    $grid .= $customFunction;
    }
    }

    //Set Grid Height
    $grid .= “$(‘#$buildDivName’).setGridHeight($buildGridHeight,true);”;
    $grid .= “$(‘.ui-jqgrid-titlebar-close’,'#gview_$buildDivName’).remove();”;
    $grid .= “”;
    return $grid;
    }
    }

    My Controller file

    load->helper(‘grid_helper’);
    $this->load->helper(‘url’);
    $this->load->model(‘customer_model’);
    }

    public function index() {
    $aData1 = array(
    ‘set_columns’ => array(
    array(
    ‘label’ => ‘Customer ID’,
    ‘name’ => ‘custid’,
    ‘width’ => 100,
    ‘size’ => 10
    ),
    array(
    ‘label’ => ‘Customer Name’,
    ‘name’ => ‘custname’,
    ‘width’ => 220,
    ‘size’ => 10
    ),
    array(
    ‘label’ => ‘Status’,
    ‘name’ => ‘custstatus’,
    ‘width’ => 100,
    ‘size’ => 10
    )
    ),
    ‘div_name’ => ‘grid1′,
    ‘source’ => ‘index.php/customer/customerList/’,
    ‘sort_name’ => ‘custname’,
    ‘pager’ =>’pager1′,
    ‘add_url’ => ‘index.php/customer/exec/add’,
    ‘edit_url’ => ‘index.php/customer/exec/edit’,
    ‘delete_url’ => ‘index.php/customer/exec/del’,
    ‘caption’ => ‘Customer Maintenance – 1′,
    ‘primary_key’ => ‘custid’,
    ‘grid_height’ => 230,
    );

    $aData2 = array(
    ‘set_columns’ => array(
    array(
    ‘label’ => ‘Customer ID’,
    ‘name’ => ‘custid’,
    ‘width’ => 100,
    ‘size’ => 10
    ),
    array(
    ‘label’ => ‘Customer Name’,
    ‘name’ => ‘custname’,
    ‘width’ => 220,
    ‘size’ => 10
    ),
    array(
    ‘label’ => ‘Status’,
    ‘name’ => ‘custstatus’,
    ‘width’ => 100,
    ‘size’ => 10
    )
    ),
    ‘div_name’ => ‘grid2′,
    ‘source’ => ‘index.php/customer/customerList/’,
    ‘sort_name’ => ‘custname’,
    ‘pager’ =>’pager2′,
    ‘add_url’ => ‘index.php/customer/exec/add’,
    ‘edit_url’ => ‘index.php/customer/exec/edit’,
    ‘delete_url’ => ‘index.php/customer/exec/del’,
    ‘caption’ => ‘Customer Maintenance – 2′,
    ‘primary_key’ => ‘custid’,
    ‘grid_height’ => 230
    );

    $data['customerGrid1'] = buildGrid($aData1);
    $data['customerGrid2'] = buildGrid($aData2);
    $this->load->view( ‘workspace’,$data );
    }

    public function customerList() {
    buildGridData(
    array(
    ‘model’ => ‘customer_model’,
    ‘method’ => ‘getAllCustomers’,
    ‘pkid’ => ‘custid’,
    ‘columns’ => array( ‘custid’,'custname’,'custstatus’)
    )
    );
    }

    }

    Please let me know how, ?? am stuck..!! :(

  17. yogi says:

    i have download a working demo,but I haven’t got it working yet, but it isn’t giving any error messages either,my browser is blank,help me please,i am a newbie.thanx

    • kugutsumen says:

      Hi yogi, I think its better if you can check in your PHP logs? My boss always tells me that “logs is your window to the universe” or better yet try setting this in your php.ini

      1
      error_reporting = E_ALL | E_STRICT

      hope this helps
      thanks,
      Mark

      • yogi says:

        i use xampp 1.7.4 and default setting is E_ALL | E_STRICT.i try take look the source at running then i find but in folder js there isn’t supplierautoload.css , please let me know,thanx a lot

  18. kugutsumen says:

    can you check on your database connection? (in config/database.php)
    its ok to remove the include of supplier-autoload.css in /view/components/header.php and include of supplier-autoload.js in
    /view/components/footer.php

    hoping that this would fix your problem,
    thanks,
    Mark

    • yogi says:

      this is my config/database.php setting

      $active_group = ‘default’;
      $active_record = TRUE;

      $db['default']['hostname'] = ‘localhost’;
      $db['default']['username'] = ‘root’;
      $db['default']['password'] = ”;
      $db['default']['database'] = ‘jqgriddemo’;
      $db['default']['dbdriver'] = ‘mysql’;
      $db['default']['dbprefix'] = ”;
      $db['default']['pconnect'] = TRUE;
      $db['default']['db_debug'] = TRUE;
      $db['default']['cache_on'] = FALSE;
      $db['default']['cachedir'] = ”;
      $db['default']['char_set'] = ‘utf8′;
      $db['default']['dbcollat'] = ‘utf8_general_ci’;
      $db['default']['swap_pre'] = ”;
      $db['default']['autoinit'] = TRUE;
      $db['default']['stricton'] = FALSE;
      I try to set profiler on supplier controller $this->output->enable_profiler(TRUE) and then i found
      DATABASE: jqgriddemo QUERIES: 0
      No queries were run,
      please help me,
      thanx

  19. yogi says:

    hai mark, i forgot set base_url in config/config.php, i’m sorry about that

    $config['base_url'] = ‘/’ // it’s your setting

    and then i change it to

    $config['base_url'] = ‘http://localhost/jqgriddemo/‘ // my setting in localhost

    but i still don’t understand why there’s no data in my supplier maintenance or there is no query
    please let me know why it happen
    thanx

  20. Nancy says:

    Thanks for the share!
    Nancy.R

  21. Anders says:

    Hi Mark!

    The grid is working rather nicely now, apart from the sorting default that I cannot get to work. Also, I was wondering if there is an easy way to update/refresh the grid after e.g. a delete, preferably with the same “settings” as before? I.e. if a user is on page 3, page 3 should refresh, or if the user has sorted on say, date, the same sort should apply after the refresh? If not, just adding a refresh after the delete would be nice, if you could describe how that’s done with the helper. Thanks!

    Anders

  22. ken says:

    I am not having success running the demo. I used the following steps…
    1. I downloaded the demo and extracted into its own directory.
    2. I created a database and imported the data given in the folder.
    3. Updated config/database.php to point to local database.
    4. Updated config/config.php with base url.
    5. Had to update 1 line in supplier controller as the grid helper file was named jqgrid in the download.

    Have I missed something here???

  23. ken says:

    Addl info…

    I do see the grid, but there is no data loaded…

    • kugutsumen says:

      any php log errors?
      i’ll try to re-check again my demo file if its working…

      thanks…
      Mark

      • ken says:

        Nothing of interest. I am running on FF. I looked at the ‘developer’ messages. A few things like css attributes ignored, but nothing that looks like it would prevent data from being loaded. You did know about the gridhelper to jqgridhelper in suppplier controller??

  24. ken says:

    Also, just fyi, when I downloaded the demo, in the config/database file it is pointing to your database. I actually ran it right out of the box initially and got an error in database. Not sure id that is what you want people downloading or not…

  25. abd hamid says:

    I’ve tried jqgrid, but I found the error message is: “An Error Was Encountered
    Unable to load the requested file: helpers / grid_helper.php “. What is the cause of the error message. Please enlightenment

  26. Pedro says:

    Hi, wonderfull work, please can you explain the directories for each libreries used JQuery, CSSs, jqgrid… thanks

  27. Pedro says:

    Hi, wonderfull work, please can you explain the directories for each libreries used JQuery, CSSs, jqgrid… thanks

  28. Joseph says:

    I am having an issue with getting the data to populate the table, but there are no errors being displayed. I noticed a few others had a similar issue but there was no resolution posted. Is there anything to solve this problem? the table is displaying properly but there is no data loading. Any guidance would be appreciated.

  29. vivek says:

    i am also having issue with getting data .There is no data populated in the grid and when i see the page source it contains two extra files “supplier-autoload.css” and supplier-autoload.js
    but both these files are missing .

    i try to print the content of the suppliergrid in the controller but this is return an empty array $data['supplierGrid'] = buildGrid($aData);

    plz help to resolve this issue

  30. vivek says:

    i got the following errror while implementing your steps
    can u help me

    SELECT * FROM tbl_category where true order by

  31. hey vivek,

    some problem to me …
    solved replacing in getAllCustomers($paramArr) function explained with :

    $sortField = (isset($paramArr['sortField']) && $paramArr['sortField'] != ”)?$paramArr['sortField']:’name’;

    $sortOrder = (isset($paramArr['sortOrder']) && $paramArr['sortOrder'] != ”)?$paramArr['sortOrder']:’asc’;

    $whereParam = (isset($paramArr['whereParam']) && $paramArr['whereParam'] != ”)?$paramArr['whereParam']:NULL;

    Good luck !

  32. marbo says:

    Great work!
    is there any chance to have export to pdf function?

    Thanks

  33. Gyorgyi says:

    The same issues as vivek and Joseph.

    This example simply won’t work. The table loads but does not populate with data.

    In firebug I got errors: supplier-autoload.js does not load, also in the XHR section: the path/source supplier/supplierList/ is not found.

  34. Milan says:

    Vivek just try to add index.php in url.
    In model try with this $whereClause order by ‘$sortField’ $sortOrder $optLimit “;

  35. munko says:

    Hi thank you for your tutorial.
    Is it possible to implement a multi search based on your code?
    I’m trying to learn codeigniter+jqgrid, can manage to get form to post the variables
    like this

    filters:{“groupOp”:”AND”,”rules”:[{"field":"student_name","op":"eq","data":"jason"},{"field":"age","op":"lt","data":"20"}]}

    and adding slight modification on grid_helper.php

    /*
    $searchField = $CI->input->get(‘searchField’);
    $searchString = $CI->input->get(‘searchString’);
    $searchOperator = $CI->input->get(‘searchOper’);
    */
    $jsondata = json_decode($CI->input->get(‘filters’);
    $groupOp = $jsondata->groupOp; // -> it will output “AND” operand
    $multidata = $jsondata->rules; // -> it will create array like this
    Array
    (
    [0] => stdClass Object
    (
    [field] => student_name
    [op] => eq
    [data] => json
    )

    [1] => stdClass Object
    (
    [field] => age
    [op] => lt
    [data] => 20
    )

    )

    i need help on how to implement those data to be put on buildWhereClauseForSearch($searchField,$searchString,$searchOperator)

    thank you for your time

    regards,
    munko

  36. Ali says:

    Dear All,

    I have same issue with getting data, There is no data populated in the grid,

    Please help me.

    Regards,
    Ali

  37. riya says:

    hi,
    can anyone tell me how to set coloumn chooser functionality in header rather than using it in its default location i.e. navigator (pager)…

  38. R.Gökhan AYBERK says:

    “download demo” link broken.
    Could you mail me “jqgriddemo.zip” file ?

  39. Beau Vazquez says:

    Nice post, keep up with this interesting work. It really is good to know that this topic thanks for taking this!

  40. Hiram Burke says:

    Thanks for the above information jqgrid with codeigniter by giving a brief description and letting the customer know about the coding.

  41. Av says:

    how to implement the search toolbar i.e column search in this

  42. Hi,
    Great work.
    Is it possible to do grouping here the way it is done on the official demo page.

  43. Albiréo says:

    Hi,
    I added some features :
    - Action parameter on click on a line,
    - Action parameters on double-click on a line,
    - pager parameter if there are more than one grid in a page.

    First, in jqgrid_lib :
    1) Private variables added in the class :
    private $functionOnDblClick;
    private $functionOnSelectRow;
    private $pager;

    2) Setters added in the class :
    public function setFunctionOnDblClick($onDblClick) {
    $this->functionOnDblClick = $onDblClick;
    }
    public function setFunctionOnSelectRow($onSelectRow) {
    $this->functionOnSelectRow = $onSelectRow;
    }
    public function setPager($pager) {
    $this->pager = $pager;
    }

    3) Build variables added in the buildGrid function :
    $buildFunctionDblClick = $this->functionOnDblClick;
    $buildFunctionSelectRow = $this->functionOnSelectRow;
    $buildPager = $this->pager;

    4) All three parameters inserted in the construction of the $grid string :
    $grid .= “$(‘#$buildDivName’).jqGrid({
    ……..
    pager: $buildPager,
    ……..
    if(!empty($buildFunctionDblClick)) {
    $grid .= ”
    ondblClickRow: function(id) {
    “.$buildFunctionDblClick.”(id);
    }”;
    if(!empty($buildFunctionSelectRow))
    $grid .= “,”;
    }
    if(!empty($buildFunctionSelectRow)) {
    $grid .= ”
    onSelectRow: function(id) {
    “.$buildFunctionSelectRow.”(id);
    }”;
    }
    …………
    Notice that ‘pager’ is mandatory.

    Then in jqgrid_helper :
    1) Call of the setters in buildGrid function :
    if( isset( $aData['pager'] ) ) $jqGrid->setPager( ‘\’#’ . $aData['pager'] . ‘\” ); // # is automatically added ; no need in the parameter.
    if( isset( $aData['functionDblClick'] ) ) $jqGrid->setFunctionOnDblClick($aData['functionDblClick']);
    if( isset( $aData['functionSelectRow'] ) ) $jqGrid->setFunctionOnSelectRow($aData['functionSelectRow']);

    That’s all !

    No ! That’s not all : insert, if necessary, your ‘onclick’ or/and ‘ondoubleclick’ (names are free) in the javascript of the webpage.

    ^_^

  44. maxim says:

    hi, great work.
    can anyone tell me because i see an error in firebug: TypeError: b.browser is undefined.

    thanks for share.

  45. Porkabul says:

    Hello and thx,

    I have an error in the online demo : (jquery version pb ?)
    TypeError: $.browser is undefined
    [Stopper sur une erreur]

    isMSIE = $.browser.msie ? true:false,

  46. Porkabul says:

    The demo works with jquery 1.8, not with 1.9

    • kugutsumen says:

      Thanks for figuring whats wrong! =D I’ll update to the latest versions of jqgrid and jquery and see if this would fix the problem else we’ll stick with 1.8 until we see a stable combination between jqgrid and jquery.

      Thanks!

  47. Hernando says:

    Hi kugutsumen and thanks for your work, i’ve set all the cofiguration but i still can´t see the the grid, working with firebug i found this: ReferenceError: $ is not defined

    $(‘#grid’).jqGrid({

    could you please help me fix this error

  48. Ileana says:

    Hello.

    I was having problems because I did not see the data. The error was

    Not found http://localhost/jqgriddemo/supplier/supplierList/?_search=false&nd=1376952644788&rows=20&page=1&sidx=supname&sord=asc

    I added index.php in the code (controllers/supplier.php)
    ‘source’ => ‘index.php/supplier/supplierList/’,

    and it works for me.

Leave a Reply