Jqgrid for Dummies


Here is a quick snippet of how to using JqGrid for dummies, like get data, delete data, access data or data manipulation.

Setup JQGrid:

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
$(document).ready(function() {
    // Enable tooltips
$("body").tooltip({
    selector : ‘[data-toggle="tooltip"]’
});
$(".chosen").chosen();

var permission = $(‘.permission’);

// Define ID for table
var selector = "#table-index";
var pager = ‘#table-pager’;

// Setup url ajax for loading data in table
var url = $(selector).data(‘url’);

// Define last sel for edit
var lastSel;

var colModel =  [
     {name:’id’, hidden: true, key:true, editable:true},
     {name:’uuid’, hidden: true},
     {name:’hybrid’, label:’Hybrid’, editable: true, editrules:{number: true}, classes: ‘numberonly’},
     {name:’some_date’, label:’Date Selection’, editable: true,  editoptions:{size:20,
          dataInit:function(el){
                $(el).datepicker({dateFormat:’dd-mm-yy’});
          },
          defaultValue: function(){
            var currentTime = new Date();
            var month = parseInt(currentTime.getMonth() + 1);
            month = month <= 9 ? "0"+month : month;
            var day = currentTime.getDate();
            day = day <= 9 ? "0"+day : day;
            var year = currentTime.getFullYear();
            return day+"-"+month + "-"+year;
          }
        }
      },
 ];

/**
 * Setup Table GRID
 *
 * We need to define colModel with editable and edittype
 * Check to load pager and bind keys
 */
var tableGrid = $(selector).jqGrid({
    url : url,
    datatype : "json",
    colModel : colModel,
    rowNum : 100,
    rowList : [100, 500, 1000],
    pager : pager,
    sortname : ‘id’,
    sortorder : "desc",
    height: 300,
    jsonReader : {
        repeatitems: false,
        id: "0"
    },
    editurl: $(selector).data(‘edit-url’),
    viewrecords: true,
    multiselect: true,
    onSelectRow: function(id){
         if(id && id!==lastSel){
            $(selector).restoreRow(lastSel);
            lastSel=id;
         }
   },
});


Always make sure to define “key” and editable to solved issue return ID of row instead of ID of data.

1
{name:’id’, hidden: true, key:true, editable:true} // IMPORTANT!

1. How to get cell value from ROW ID

1
2
3
4
5
// Get cell data for selected row ID
selRowId = $(selector).jqGrid (‘getGridParam’, ‘selrow’),

// Get debit colModel value
debitCelValue = $(selector).jqGrid (‘getCell’, rowid, ‘debit’);

2. Set value cell

1
2
3
4
// Set all invoice data to `0` if no invoice number selected.
$selectorMaterial
 .jqGrid("setCell", lastSelMaterial, "code", val.code)
 .jqGrid("setCell", lastSelMaterial, "unit",val.unit);

3. Add new record in JqGrid

We are using $.jgrid.randId() to generate new unique ID.
We can the value with existing ID data.

1
2
3
4
5
6
7
8
9
/**
 * Add new record in tables
 */
function addNewRow(selector, initialData) {
    // Iterate initial data and add rows by new index
    for(var i=0;i<=initialData.length;i++) {
        $(selector).jqGrid(‘addRowData’, $.jgrid.randId(), initialData[i]);
    }
}

4. Counting total Rows in Footer

1
var totalRows = $(selector).getGridParam("reccount");

5. Manipulate all rows data by input form in header
Let say we have select input for ‘teacher’, ‘student ‘ and ‘class’. We want to update current data with select value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var allRowsInGrid = $(selector).jqGrid(‘getGridParam’,’data’);

for (var i = allRowsInGrid.length – 1; i >= 0; i–) {
    console.log(allRowsInGrid[i].id + ‘ ‘ + i);
    if(allRowsInGrid[i].id.length>0) {
         var rowData = $(selector).jqGrid(‘getRowData’, allRowsInGrid[i].id);

        // Setup id
        rowData.id = allRowsInGrid[i].id;

        // Overwrite value row data
        rowData.student= $(‘#id_student option:selected’).text();
        rowData.teacher= $(‘#id_teacher option:selected’).text();
        rowData.class= $(‘#id_class option:selected’).text();

        // Update row with form header data
        $(selector).jqGrid(‘setRowData’, allRowsInGrid[i].id, rowData);
    }
}

6. Adding class in columns and cell

1
2
3
4
colModel : [
           {name:’id’, hidden: true},
           {name:’uuid’, hidden: true},
           {name:’debit’, label:’Debit’, editable: true, editrules:{number: true}, classes: ‘numberonly’}

7. Close currently inline edit form programmatically
Usually before execute button for save or delete, we should close any active inline edit form.

1
2
3
// IMPORTANT! we should make sure no editable input still opened
// Cancel currently editing row to avoid sending input to AJAX
$selector.jqGrid(‘restoreRow’, lastSel);

7. Reset Selected Rows

1
$selector.jqGrid(‘resetSelection’);

8. Update URL Dynamically and reload

1
2
$selectorFarmfield.setGridParam({url: ‘your-url’});
$selectorFarmfield.trigger("reloadGrid");

9. Get current ROW ID

1
rowid = $selector.jqGrid(‘getGridParam’, ‘selarrrow’);

10. Select on change

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
{name:’name’, label:’Nama’, search: false, sortable:false, editable:true,
                      edittype: "select", editrules: { required: true },
                      editoptions: {
                        value: $config.data(‘materialtype’),
                        defaultValue: ‘—-‘,
                        dataEvents: [
                            {type: ‘change’, fn: function(e) {
                                var selectedMaterial = $(this).val();
                                var selRowId = $selectorMaterial.jqGrid(‘getGridParam’, ‘selrow’);
                                var rows = $selectorMaterial.jqGrid(‘getGridParam’,’data’);

                                console.log("this is changed");

                                // Iterate
                                $.each($config.data(‘materialtype-json’), function( index, val ) {

                                    if(val.uuid == selectedMaterial) {
                                        console.log(val.unit);
                                        console.log(val.code);
                                        console.log(selRowId);

                                        // var rowData = $selectorMaterial.jqGrid(‘getRowData’, selRowId);
                                        // rowData.code = val.code;
                                        // rowData.unit = val.unit;
                                        // $selectorMaterial.jqGrid(‘setRowData’, selRowId, rowData);

                                        // Set all invoice data to `0` if no invoice number selected.
                                        $selectorMaterial
                                            .jqGrid("setCell", lastSelMaterial, "code", val.code)
                                            .jqGrid("setCell", lastSelMaterial, "unit",val.unit);

                                        // updateColumnData($selectorMaterial, selRowId, ‘uuid’, val.uuid);
                                        // updateColumnData($selectorMaterial, selRowId, ‘unit’, val.unit);
                                        // updateColumnData($selectorMaterial, selRowId, ‘code’, val.code);

                                        // auto save inline edit programmatically
                                        // $selectorMaterial.jqGrid(‘saveRow’, lastSelMaterial, false, ‘clientArray’);
                                        // Refresh table to update the value
                                        // $selectorMaterial.trigger(‘reloadGrid’);
                                    }
                                });

                            }
                          },
                        ]
                      }},

12. Update Select value when add new data
We need to declare class for colModel. Let say “dropdown” in colModel.
Then, when assignin new data

1
2
3
var newRowId = $.jgrid.randId();
$selectorMaterial.jqGrid(‘addRowData’, newRowId, initialData);
$selectorMaterial.find(‘#’ + newRowId + ‘ td.dropdown’).html(obj.materialtype__name);

13. Jqgrid make all row editable by default

1
2
3
4
5
6
7
8
9
loadComplete: function () {
    var $this = $(this), rows = this.rows, l = rows.length, i, row;
    for (i = 0; i < l; i++) {
        row = rows[i];
        if ($.inArray(‘jqgrow’, row.className.split(‘ ‘)) >= 0) {
            $this.jqGrid(‘editRow’, row.id, true);
        }
    }
}

11. Get data from remote and use local afterward
When we need to fetch data from server, but then edit as local, we just need to put this variable in config :

1
loadonce:true

14. Save all rows at once

1
2
3
4
5
6
    total = $selector.getGridParam("reccount");
    data = $selector.jqGrid(‘getDataIDs’);

    for (i = 0; i < total; i++) {
        $selector.jqGrid(‘saveRow’, data[i], false, ‘clientArray’);
    }

15. Get all rows ID

1
data = $selector.jqGrid(‘getDataIDs’);

14. Custom validation from another column

1
2
3
4
5
6
7
8
9
                function validateBooking(value) {
                    var localrow = $selectorMaterial.jqGrid("getLocalRow", lastSelMaterial);

                    if (localrow.available < value) {
                        return [false, "Booking melebihi batas tersedia"];
                    }
   
                    return [true, ""];
                }

16. Make Inline Edit Auto Reload After save

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
ondblClickRow: function(row_id){ // Handle inline edit
                if(row_id && row_id!==lastSelChild){
                    $selectorChild.restoreRow(lastSelChild);
                    lastSelChild=row_id;
                 }
                // add csrf token middleware in inline edit submission data
                 var editparameters = {
                    extraparam: {
                        csrfmiddlewaretoken: $(‘.token-data’).data(‘token’),
                        fnlov: selectedUUID
                    },
                    keys: true,
                    aftersavefunc: function (rowid) {
                        // Get cell data for selected row ID
                        selRowId = $selectorChild.jqGrid(‘getGridParam’, ‘selrow’);
                        var rowData = $selectorChild.jqGrid(‘getRowData’, rowid);

                        // After inline edit, it will give value UUID
                        // We need to convert it back into text values
                        var rowUpdate = {
                            fnaccount: convertValueAccount($config.data(‘account’), rowData, ‘fnaccount’),
                            fnsegment_company: convertValueSegment($config.data(‘company’), rowData, ‘fnsegment_company’),
                            fnsegment_businessunit: convertValueSegment($config.data(‘businessunit’), rowData, ‘fnsegment_businessunit’),
                            fnsegment_region: convertValueSegment($config.data(‘region’), rowData, ‘fnsegment_region’),
                            fnsegment_unit: convertValueSegment($config.data(‘unit’), rowData, ‘fnsegment_unit’),
                            fnsegment_department: convertValueSegment($config.data(‘department’), rowData, ‘fnsegment_department’),
                            fnsegment_subdepartment: convertValueSegment($config.data(‘subdepartment’), rowData, ‘fnsegment_subdepartment’)
                        };
                       
                        // one ca call setRowData below with two properties
                        // only which are required for
                        $selectorChild.jqGrid("setRowData", rowid, rowUpdate);

                        tableGridChild.trigger("reloadGrid");
                    }
                  };

                 $selectorChild.jqGrid(‘editRow’, row_id, editparameters);
            }

17. Error return ID in select dropdown

When we got ID instead of name in inline edit dropdown, usually because one of field we use

1
formatter: "select"

in colModel attribute inline.

To solve this, in ColModel attribute, put classes and use

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ondblClickRow: function(row_id){ // Handle inline edit
    if(row_id && row_id!==lastSelMaterial){
        $selectorMaterial.restoreRow(lastSelMaterial);
        lastSelMaterial=row_id;
     }
    // add csrf token middleware in inline edit submission data
    var editparameters = {
        extraparam: {csrfmiddlewaretoken: $(‘.token-data’).data(‘token’)},
        keys: true,
        aftersavefunc: function processData(rowid, response, options) {

            // update dropdown value from UUID into name beacuse we using formatter select
            // make sure to put classes "materialtype__name" in colModel materialtype__name
            rowData = $selectorMaterial.getRowData(rowid);
            $selectorMaterial.find(‘#’ + lastSelMaterial + ‘ .materialtype__name’).html(rowData.name);

            countTotalMaterial(rowid);

        },
    };
    $selectorMaterial.jqGrid(‘editRow’, row_id, editparameters);
}

18. Delete multiple rows Jqgrid
There is a bug in delete rows in Jqgrid, the correct way is by delete by reverse way :

1
2
3
4
5
6
// Get selected row and delete locally
var rows = tableGridMaterial.jqGrid(‘getGridParam’,’selarrrow’);

for (var i = rows.length – 1; i >= 0; i–) {
   $selectorMaterial.jqGrid(‘delRowData’, rows[i]);
}

19. Enable select inline and filter

1
2
3
{name:’aprule_status’, label:’Status’, search: true, sortable:false, width:140,
stype: ‘select’, searchoptions: { value: $config.data(‘apstatus-choices’)},
editable: true, edittype:’select’, editoptions:{value:$config.data(‘apstatus-choices’)}},

20. Enable datepicker inline-edit

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
/**
 * Configuration date picker for jqgrid editable
 * Correct function
 */
function editableDate($selector) {
    var editableVar = {
        size : 20,
        dataInit: function (element) {
                $(element).datepicker({
                    dateFormat : ‘dd-mm-yy’,
                    onSelect: function(dateText, inst) {
                        var $input = inst.input; // the datepicker input
                        var $row = $input.parents("tr");
                        $selector.jqGrid(‘saveRow’,$row.attr("id"), false);
                    }
                });
        },
        defaultValue : function() {
            var currentTime = new Date();
            var month = parseInt(currentTime.getMonth() + 1);
            month = month <= 9 ? "0" + month : month;
            var day = currentTime.getDate();
            day = day <= 9 ? "0" + day : day;
            var year = currentTime.getFullYear();
   
            return day + "-" + month + "-" + year;
        }
    };
   
    return editableVar;
}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.