Tuesday, April 5, 2011

JQuery-Plugin, JQGrid - Methods and Events

Hey...

We worked on jqGrids installing, setup and properties in my last post. Here I'm going to explain more feature of jqGrid(including Events and Methods) and extend my last sample of jqGrid.


7.1.2 Events
The action to take on an event is set as a property of the grid, e.g.
onSelectRow: function(id){
  if(id && id!=lastSel){
    $('#tbleditable').restoreRow(lastSel);
    lastSel=id;
  }
  $('#tbleditable').editRow(id, true); }, 
The above example specifies the action to take when a row is selected. The following one shows how to use onSortCol:
onSortCol: function( index, colindex, sortorder) {
    // here is the code
  }
The events that you can use to perform some additional action are listed here, in alphabetic order:
EventParametersDescription
afterInsertRowrowid,
rowdata,
rowelem
This event fires after every inserted row.
  • rowid is the id of the inserted row
  • rowdata is an array of the data to be inserted into the row. This is array of type name: value, where the name is a name from colModel
  • rowelem is the element from the response. If the data is xml this is the xml element of the row; if the data is json this is array containing all the data for the row 
gridCompletenone This fires after all the data is loaded into the grid and all other processes are complete
loadBeforeSendxhrA pre-callback to modify the XMLHttpRequest object (xhr) before it is sent. Use this to set custom headers etc. The XMLHttpRequest is passed as the only argument.
loadCompletenoneThis event is executed immediately after every server request
loadErrorxhr,st,errA function to be called if the request fails. The function gets passed three arguments: The XMLHttpRequest object (XHR), a string describing the type of error (st) that occurred and an optional exception object (err), if one occurred.
onCellSelectrowid, iCol,
cellcontent
fires when we click on particular cell in the grid rowid is the id of the row iCol is the index of the cell cellcontent is the content of the cell. (Note that this available when we not use cell editing module and is disabled when using cell editing). Important note regarding IE6: this event may exhibit strange behaviours because of a bug in early IE6 releases. When we have a hidden column the index will not be calculated correctly. You can avoid using this feature in a grid with hidden columns, test for these browsers and conditionally suppress this feature, or suggest that your IE6 users upgrade.
ondblClickRowrowidRaised immediately after row was double clicked.
Calling convention:
ondblClickRow: function( rowid) {
    // here is the code
  }
onHeaderClickgridstateCan be used when clicking to hide or show grid; gridstate is the state of the grid (visible or hidden)
onRightClickRowrowidRaised immediately after row was right clicked.
onSelectAllarray of the
selected ids
This event fires (if defined) when multiselect is true and you click on the header checkbox. Parameter passed to this event is array of selected rows. If the rows are unselected, the array is empty.
onSelectRowrowidRaised immediately after row was clicked.
onSortColindex,
colindex,
sortorder
Raised immediately after sortable column was clicked and before sorting the data
  • index is the index name from colModel  
  • colindex is the index of column  
  • sortorder is the sorting order - can be 'asc' or 'desc'

7.1.3 Methods 
Calling Convention:
$("#grid_id").jqGridMethod( parameter1,...parameterN ) 
Where:
  • grid_id is the id of the already constructed jqGrid. 
  • jqGridMethod is a method applied to this jqGrid. 
  • parameter1,...parameterN - a list of parameters 
IMPORTANT: Some 'get' and 'set' methods (e.g., getUrl()) supported up to version 3.1 have been removed in version 3.2 and replaced by more generic methods (e.g., getGridParam(url) or setGridParam({url:value}) ).

Where a method is not designed to return a requested value, then what is returned is the jqGrid object and a set of such methods can be chained, e.g.,
$("#grid_id").setGridParam({..}).hideCol("somecol").trigger("reloadGrid")
MethodParametersReturnsDescription
addJSONDatadatatrue on
success,
otherwise
false
Populates a grid with the passed data (an array). Suppose we have data from a particular webservice (jsonresponse), then

var mygrid = jQuery("#"+grid_id)[0];
var myjsongrid =
eval("("+jsonresponse.responseText+")");
mygrid.addJSONData(myjsongrid);
myjsongrid = null; j
sonresponse =null;

will populate the data to the grid. And, of course, the data in myjsongrid can be manipulated before being passed to addJSONData.

addJSONData is a privileged method.
addRowDatarowid, data,
position (first,
last, before,
after - default
last), srcrowid
(source row,
applies only
when position
is either
before or
after)
true on
success,
otherwise
false
Inserts a new row with id = rowid containing the data in data (an array) at the position specified (first in the table, last in the table or before or after the row specified in srcrowid). The syntax of
the data array is: {name1:value1,name2: value2…} where name is the name of the column as described in the colModel and the value is the value.
addXmlDataxmlresponsetrue on
success,
otherwise
false
Populates a grid with the passed data. Suppose we have data from a particular webservice (xmlresponse), then

var mygrid = jQuery("#"+grid_id)[0];
mygrid.addXmlData(xmlresponse.responseXML);

will populate the data to the grid. And, of course, the data in xmlresponse can be manipulated before being passed to addXmlData.

addXmlData is a privileged method.
clearGridDatanonejqGrid
object
Clears the currently loaded data from grid
delRowDatarowidtrue on
success,
otherwise
false
Deletes the row with the id = rowid. This operation does not delete a data from the server.
FormToGridrowid, formidjqGrid
object
Reads data from a form (previously defined in html) identified by formid and loads data into the grid in row with rowid. If the names of both grid and form are the same the data from the form
replaces the data in the grid. Note that all fields from grid can be replaced, including hidden. This is the opposite of GridToForm
getCellrowid, iCol the
content of
the cell
iCol can be either the column index or the name.
getDataIDs nonearray of
the id's in
the current
grid view.
Empty
array if no
data is
available.

getGridParamnamethe value
of the
requested
parameter.
name is the name from options array. For a particular options, see below. If the name is not set the entry options are returned.
getRowDatarowidarray with
data of the
requested
id = rowid.
The returned array is of type name:value, where the name is a name from colModel and the value is a actual value. Returns empty array if the row can not be found.
GridToFormrowid, formidjqGrid
object
Reads data from the given rowid and fills the form (previously defined in html) identified by formid. If the names of both grid and form are the same the data from the grid replaces the data in the form. Note that all fields from grid can be used, including hidden.
hideColcolnamejqGrid
object
Hides a column with a given colname. If the colname is a string, only the specified column is hidden. If the colname is array of type
["name1","name2"] then the columns with names 'name1' and 'name2' will be hidden at the same time. The names in colname must be valid names from the colModel. The width of the grid is
changed according to the following rules: if the grid currently has no horizontal scroll bar, the width of the grid is decreased by the width of the hidden column(s). If a scrollbar is visible, the width is adjusted which may or may not change the width of the grid.
resetSelectionnonejqGrid
object
Resets (unselects) the selected row(s). Also works in multiselect mode.
setCaptioncaptionjqGrid
object
Sets a new caption of the grid. If the Caption layer was hidden, it is shown.
setCellrowid,
colname,
data, class,
properties
jqGrid
object
This method can change the content of particular cell and can set class or style properties. Where:
  • rowid: the id of the row,  
  • colname: the name of the column (this parameter can be a number beginning from 0)  
  • data: the content that can be put into the cell. If empty string the content will not be changed  
  • class: if class is string then we add a class to the cell using addClass; if class is an array we set the new css properties via css  
  • properties: sets the attribute properies of the cell  

Example :

setCell("10", "tax", '', {color:'red','text-
align':'center'}',{title:'Sales Tax'})

will set the contents of the tax field in row 10 to red and centered and change the title to 'Sales Tax'.
setGridParamobjectjqGrid
object
Sets a particular parameter. Note - for some parameters to take effect a trigger("reloadGrid") should be executed. Note that with this method we can override events like onSelectRow, etc.
Example:
setGridParam({
url:"newurl",
page:1,
onSelectRow:function(id){/*here is the new
code*/}
});
The name (in the name:value pair) is the name from options array. For a particular options, see below. If the name is not set the entry options are returned.
setGridHeightnew_heightjqGrid
object
Sets the new height of the grid dynamically. Note that the height is set only to the grid cells and not to the grid. <>new_height<> can be in pixels, percentage, or 'auto'
setGridWidthnew_width,
shrink
jqGrid
object
Sets a new width to the grid dynamically. The parameters are:
  • new_width is the new width in pixels.
  • shrink (default true) has the same behavior as shrinkToFit 
setLabelcolname,
newlabel,
sattr
jqGrid
object
Sets a new label in the header for the specified column; can also set attributes and classes (sattr). The parameters are:
  • colname(mixed) is either the name of the column (from colModel) or the number of the column in colModel beginning from 0.  
  • newlabel(string) is the label that we want to change. Can be a empty string.
  • sattr(mixed) - if this parameter is array - we add this as attributes to this header element. if the parameter is string we add a class to this element
setRowData rowid, datatrue on
success,
otherwise
false
Updates the values (using the data array) in the row with rowid. The syntax of data array is: {name1:value1,name2: value2…} where the name is the name of the column as described in the colModel and the value is the new value.
setSelectionrowid,
onsetselection
jqGrid
object
Toggles a selection of the row with id = rowid; if onsetselection is true (the default) then the event onSetRow is launched, otherwise it is not
showColcolnamejqGrid
object
Shows a column with a given colname. If the colname is a string we show only the specified column. If colname is array of type ["name1","name2"] then the columns with names 'name1' and 'name2' will be shown at the same time The names in colname must be valid names from colModel. The width of the grid changes by the width of the newly-shown columns.
.trigger("reloadGrid")nonejqGrid
object
Reloads the grid with the current settings. This means that a new request is send to the server if datatype is xml or json. This method should be applied to an already-constructed grid - e.g.,  $("#grid_id").trigger("reloadGrid");

getGridParam
OptionReturns
getGridParam("url")the current url from options array
getGridParam("sortname")the name of last sorted column
getGridParam("sortorder")the last sorted order
getGridParam("selrow") the id of the selected row, null if row is not selected
getGridParam("page") the current page number.
getGridParam("rowNum") the current number of requested rows
getGridParam("datatype") the current datatype.
getGridParam("records") the current number of records in grid.
getGridParam("selarrrow")array of id's of the selected rows when multiselect options is true. Empty array if not selection.
setGridParam
MethodDescription
setGridParam({url:newvalue})Parameters: url - string Set a new url, replacing the older.
setGridParam({sortname:newvalue})Parameters: sortname - string Set a new sort name
setGridParam({sortorder:newvalue})Parameters: sortorder - string (asc or desc) Set a new sort order
setGridParam({page:newvalue})Parameters: rownum - integer > 0 Set a new number of requested rows.
setGridParam({rowNum:newvalue})Parameters: rownum - integer > 0 Set a new number of requested rows.
setGridParam({datatype:newvalue})Parameters: datatype - string (xml,json.xmlstring,jsonstring, clientSide) Set a new datatype.

7.1.4 Advanced Methods 
Advanced methods offer the ability to dynamically change properties of the colModel. To keep the basic code small, these reside in a separate module (grid.custom.js) that must be installed for these to be available.
MethodParametersReturnsDescription
getColPropcolnamean array
of the
properties
of the
given
column
from
colModel

GridDestroygrid_idtrue on
success,
otherwise
false
Destroys the entry grid from the DOM (clears all the html associated with the grid and unbinds all events)
GridUnloadgrid_idtrue on
success,
otherwise
false
The only difference to previous method is that the grid is destroyed, but the table element and pager (if any) are left ready to be used again.
setColPropcolname,
properties
jGrid
object
Sets new properties in colModel. This method is ideal for dynamically changing properties of the column. Note that some properties - like width and align - have no effect. For example:
jQuery("#grid_id").
setColProp('colname',{editoptions:{value:"True:False"}})
will change the editoptions values.
sortGridcolname,reloadjGrid
object
Sorts the given colname and shows the appropriate sort image. The same (without sorting image) can be done using  setGridParam({sortname:'myname'}).trigger('reloadGrid')  If the reload is set to true, the grid reloads with the current page and sortorder settings.

7.1.5 Obsolete Methods
The following methods, all part of jqGrid up to and including version 3.1, have been removed starting with version 3.2, replaced by a more generic method. 
'Get' MethodsReturnsUse Instead
getUrlthe current url from options arraygetGridParam("url")
getSortNamethe name of last sorted columngetGridParam("sortname")
getSortOrderthe last sorted order
getSelectedRowthe id of the selected row, null if row is not selected getGridParam("selrow")
getPagethe current page numbergetGridParam("page")
getRowNumthe current number of requested rowsgetGridParam("rowNum")
getDataTypethe current datatypegetGridParam("datatype")
getRecordsthe current number of records in grid.getGridParam("records")
getMultiRowarray of id's of the selected rows when multiselect options is true. Empty array if no selection.getGridParam("selarrrow")
'Set' Methodsto setUse Instead
setUrla new url, replacing the older.setGridParam({url:newvalue})
setSortOrdera new sort ordersetGridParam({sortname:newvalue})
setPagea new page numbersetGridParam({page:newvalue})
setRowNuma new number of requested rowssetGridParam({rowNum:newvalue})
setDataTypea new datatypesetGridParam({datatype:newvalue})

Example
As you remember our previous sample has this view:
Image 1
I'm going to change it in somewhere.
User can double click any rows and if the selected row is a folder, the folder will be opened elsewhere if the selected row is file, the file will be downloaded.
The delete operation has some faults. As you know if a folder has some sub-folders or files, can not be deleted but no messages is shown to notify client. Because we use the default grid delete operation. But here I'm going to correct it via a custom delete button.

1. Double Click
$("#fileGrid").jqGrid({
            url:'${listUrl}',
            datatype:'json',
            contentType:'contentType:"application/json; charset=utf-8"',
            jsonReader:{repeatitems: false,id:"id"},
            direction:'ltr',
            width:'500',
            colNames:['','name', 'file','edit'],
            colModel:[{sortable:false, width:'20', formatter:folder},{name:'name',sortable:true},{name:'file',hidden:true},{align:'center', sortable:false, width:'50',formatter:edit}],
            rowNum:10,
            rowList:[10,20,30],
            pager:'#filePager',
            sortname:'id',
            viewrecords:true,
            multiselect:true,
            multiboxonly:true,
            sortorder:'desc',
            prmNames:{rows:'pagination.rowSizePerPage', page:'pagination.currentPage', sort:'pagination.sortIndex', order:'pagination.sortOrder'},
            caption:'File List',
            recordtext:'View {0} - {1} of {2}',
            emptyrecords:'No Records',
            loadtext:'Loading ...',
            pgtext:'Page {0} Of {1}',
            ondblClickRow: function(rowid) {
                var row = $("#fileGrid").getRowData(rowid);
                if (row.file == 'true') {
                    setFormAction('<spring:url value="/file/download.html"/>');
                    setFileId(rowid);
                    $("#fileForm").submit();
                } else {
                    setFormAction('<spring:url value="/file/list.html"/>');
                    setFolderId(rowid);
                    $("#fileForm").submit();
                }
            }
        });
As you see the red lines are double click code. I need the file field of rows. So I should first define it in colModel(the blue lines) then I use it in double click methods(red lines). The double clicked row id will pass to this method. So first I find row object(via getRowData method) then I check if the row is file or folder. If it is file, it will be downloaded elsewhere will be opened.
2. Delete
I should first define an architecture for delete. First the selected record(s) id will be sent via ajax request to the server then server tries to delete it. If the delete operation is successfully done, the client will reload the grid data to get update else the error message should be displayed to the client.
Here is the server side code in FileController class:
@RequestMapping("/delete")
@ResponseBody
public String delete(@RequestParam(value = "ids", required = true) List<Long> ids) throws IOException {
        if(!fileService.deleteAll(ids)){
            return "Your selected folder(s) contain(s) some files or folder";
        }
        return "";
}
As you see if deleteAll method returns false, the error message will be written in response body.

Here is the javascript code in file-list.jsp:
$("#fileGrid").jqGrid('navGrid', '#filePager', {search:false, edit:false, add:false, del:false}).navButtonAdd("#filePager", {
            caption:'',
            buttonicon: "ui-icon-plus",
            onClickButton:function() {
                setFormAction('<spring:url value="/file/add.html"/>');
                $("#fileForm").submit();
            },
            position:"first", title:'add'}).navButtonAdd("#filePager", {
            caption:'',
            buttonicon: "ui-icon-trash",
            onClickButton:function() {
                var selectedRowIds = $("#fileGrid").getGridParam("selarrrow");
                if (selectedRowIds.length > 0) {
                    if (confirm("Are you sure to delete the selected rows?")) {
                        var params = "";
                        for (var i = 0; selectedRowIds[i]; i++) {
                            params += "ids=" + selectedRowIds[i] + "&";
                        }
                        $.ajax({
                            type: 'POST',
                            url: '<spring:url value="/file/delete.html"/>',
                            data: params,
                            success: function(msg) {
                                if (msg != '') {
                                    alert(msg);
                                } else {
                                    $("#fileGrid").trigger("reloadGrid");
                                }

                            }
                        });
                    }
                } else {
                    alert("you should select some rows first");
                }
            },
            position:"first", title:'delete selected rows'});
    });
I get the selected rows id from grid(via getGridParam('selarrrow') method) then make request parameter in the loop with name "ids" then confirm deleting operation from the client. After confirmation, I make an Ajax request by jquery API. In success method of Ajax request, the response body will be passed in method parameter. So I check it and if it is not empty, I will show it to the client else reload the grid to get updated data from the server(Here I also can delete the selected row by myself in client side via delRowData method of jqGrid but I prefer to reload the grid to synchronize client and server data).

Source Code
It's the time to download the source code and try it yourselves. The application needed jar files are the same as previous post example. So you can copy all of them to here: [app-root]/lib/
The application database script is available in [app-root]/db/filerepository.sql. you can restore it in your mysql server. the connection datasource properties is in [app-root]/src/database.properites. And after you deploy the project in you application server (like tomcat) the home page will be: http://localhost:8080/home/view.html also file list page is: http://localhost:8080/file/list.html
the admin user specification is:
username: administrator
password: 123456
you can use it to log in for the first time.


all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

1 comment:

FOYSAL said...

Greate tutorial. i like this.

Foysal