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); },
onSortCol: function( index, colindex, sortorder) {
// here is the code
}
Event | Parameters | Description |
---|---|---|
afterInsertRow | rowid, rowdata, rowelem | This event fires after every inserted row.
|
gridComplete | none | This fires after all the data is loaded into the grid and all other processes are complete |
loadBeforeSend | xhr | A 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. |
loadComplete | none | This event is executed immediately after every server request |
loadError | xhr,st,err | A 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. |
onCellSelect | rowid, 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. |
ondblClickRow | rowid | Raised immediately after row was double clicked. Calling convention: ondblClickRow: function( rowid) {
|
onHeaderClick | gridstate | Can be used when clicking to hide or show grid; gridstate is the state of the grid (visible or hidden) |
onRightClickRow | rowid | Raised immediately after row was right clicked. |
onSelectAll | array 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. |
onSelectRow | rowid | Raised immediately after row was clicked. |
onSortCol | index, colindex, sortorder | Raised immediately after sortable column was clicked and before sorting the data
|
7.1.3 Methods
Calling Convention:
$("#grid_id").jqGridMethod( parameter1,...parameterN )
- 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")
Method | Parameters | Returns | Description |
---|---|---|---|
addJSONData | data | true 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. |
addRowData | rowid, 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. |
addXmlData | xmlresponse | true 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. |
clearGridData | none | jqGrid object | Clears the currently loaded data from grid |
delRowData | rowid | true on success, otherwise false | Deletes the row with the id = rowid. This operation does not delete a data from the server. |
FormToGrid | rowid, formid | jqGrid 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 |
getCell | rowid, iCol | the content of the cell | iCol can be either the column index or the name. |
getDataIDs | none | array of the id's in the current grid view. Empty array if no data is available. | |
getGridParam | name | the 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. |
getRowData | rowid | array 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. |
GridToForm | rowid, formid | jqGrid 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. |
hideCol | colname | jqGrid 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. |
resetSelection | none | jqGrid object | Resets (unselects) the selected row(s). Also works in multiselect mode. |
setCaption | caption | jqGrid object | Sets a new caption of the grid. If the Caption layer was hidden, it is shown. |
setCell | rowid, colname, data, class, properties | jqGrid object | This method can change the content of particular cell and can set class or style properties. Where:
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'. |
setGridParam | object | jqGrid 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. |
setGridHeight | new_height | jqGrid 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' |
setGridWidth | new_width, shrink | jqGrid object | Sets a new width to the grid dynamically. The parameters are:
|
setLabel | colname, 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:
|
setRowData | rowid, data | true 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. |
setSelection | rowid, 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 |
showCol | colname | jqGrid 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") | none | jqGrid 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
Option | Returns |
---|---|
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. |
Method | Description |
---|---|
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.
Method | Parameters | Returns | Description |
---|---|---|---|
getColProp | colname | an array of the properties of the given column from colModel | |
GridDestroy | grid_id | true on success, otherwise false | Destroys the entry grid from the DOM (clears all the html associated with the grid and unbinds all events) |
GridUnload | grid_id | true 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. |
setColProp | colname, 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. |
sortGrid | colname,reload | jGrid 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' Methods | Returns | Use Instead |
---|---|---|
getUrl | the current url from options array | getGridParam("url") |
getSortName | the name of last sorted column | getGridParam("sortname") |
getSortOrder | the last sorted order | |
getSelectedRow | the id of the selected row, null if row is not selected | getGridParam("selrow") |
getPage | the current page number | getGridParam("page") |
getRowNum | the current number of requested rows | getGridParam("rowNum") |
getDataType | the current datatype | getGridParam("datatype") |
getRecords | the current number of records in grid. | getGridParam("records") |
getMultiRow | array of id's of the selected rows when multiselect options is true. Empty array if no selection. | getGridParam("selarrrow") |
'Set' Methods | to set | Use Instead |
---|---|---|
setUrl | a new url, replacing the older. | setGridParam({url:newvalue}) |
setSortOrder | a new sort order | setGridParam({sortname:newvalue}) |
setPage | a new page number | setGridParam({page:newvalue}) |
setRowNum | a new number of requested rows | setGridParam({rowNum:newvalue}) |
setDataType | a new datatype | setGridParam({datatype:newvalue}) |
Example
As you remember our previous sample has this view:
Image 1 |
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();
}
}
});
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 "";
}
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'});
});
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:
Greate tutorial. i like this.
Foysal
Post a Comment