Table of Contents
Inline Editing
Inline editing is a quick way to update database information by making changes directly in the row of the grid, as seen in the image below:
To use Inline Editing, users select a row with the mouse. In response, jqGrid converts each editable field to a data entry cell, as seen in the Name and Price fields above. Cells that aren't editable, such as the ID field above, don't change appearance and remain read-only. Whether an individual column is editable or read-only is controlled by setting the attribute in the ColModel.
When finished, users hit the “enter” key to send the data to the server.
Software Requirement & Installation
In order to use this functionality, make sure you put a check mark by the Inline Editing and Common modules when you downloaded jqGrid. For more information refer to Download.
Note to Developers - Source code can be found in the grid.inlinedit.js file, located in the src directory.
The methods used in inline editing are a sub-set of those of the parent grid. They are described below.
Methods
For inline editing, we have five additional methods (of the Grid API) available:
- editRow
- saveRow
- restoreRow
- addRow
- inlineNav
These methods can be called, of course, only on an already-constructed grid, from a button click or from an event of the grid itself:
Example:
jQuery("#grid_id").jqGrid({ ... onSelectRow: function(id){ if(id && id!==lastSel){ jQuery('#grid_id').restoreRow(lastSel); lastSel=id; } jQuery('#grid_id').editRow(id, true); }, ... });
In this example, if another was row being edited and has not yet been saved, the original data will be restored and the row “closed” before “opening” the currently-selected row for editing (where lastSel was previously defined as a var).
If you want to save instead to restore the editing you can call saveRow in place of restoreRow.
editRow
Calling conventions:
jQuery("#grid_id").editRow(rowid, keys, oneditfunc, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc);
or when we use the new API
jQuery("#grid_id").jqGrid('editRow',rowid, keys, oneditfunc, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc);
where
- grid_id is the already constructed grid
- rowid: the id of the row to edit
- keys: when set to true we can use [Enter] key to save the row and [Esc] to cancel editing.
- oneditfunc: fires after successfully accessing the row for editing, prior to allowing user access to the input fields. The row's id is passed as a parameter to this function.
succesfunc, url, extraparam, aftersavefunc,errorfunc and afterrestorefunc are described below, in the saveRow section.
Calling with object parameter:
jQuery("#grid_id").jqGrid('editRow',rowid, { keys : true, oneditfunc: function() { alert ("edited"); } });
The default object parameter is as follow:
editparameters = { "keys" : false, "oneditfunc" : null, "successfunc" : null, "url" : null, "extraparam" : {}, "aftersavefunc" : null, "errorfunc": null, "afterrestorefunc" : null, "restoreAfterError" : true, "mtype" : "POST" } jQuery("#grid_id").jqGrid('editRow',rowid, parameters);
If keys is true, then the remaining settings – successfunc, url, extraparam, aftersavefunc, errorfunc and afterrestorefunc - are passed as parameters to the saveRow method when the [Enter] key is pressed (saveRow does not need to be defined as jqGrid calls it automatically). For more information see saveRow method below.
When this method is called on particular row, jqGrid reads the data for the editable fields and constructs the appropriate elements defined in edittype and editoptions
saveRow
Saves the edited row.
Calling convention:
jQuery("#grid_id").saveRow(rowid, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc);
or when we use the new API
jQuery("#grid_id").jqGrid('saveRow',rowid, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc);
Calling with object parameter:
jQuery("#grid_id").jqGrid('saveRow',rowid, { successfunc: function( response ) { return true; } });
The default object parameter is as follow:
saveparameters = { "successfunc" : null, "url" : null, "extraparam" : {}, "aftersavefunc" : null, "errorfunc": null, "afterrestorefunc" : null, "restoreAfterError" : true, "mtype" : "POST" } jQuery("#grid_id").jqGrid('saveRow',rowid, saveparameters);
where
- rowid: the id of the row to save
- succesfunc: if defined, this function is called immediately after the request is successful. This function is passed the data returned from the server. Depending on the data from server; this function should return true or false.
- url: if defined, this parameter replaces the editurl parameter from the options array. If set to 'clientArray', the data is not posted to the server but rather is saved only to the grid (presumably for later manual saving).
- extraparam: an array of type name: value. When set these values are posted along with the other values to the server.
- aftersavefunc: if defined, this function is called after the data is saved to the server. Parameters passed to this function are the rowid and the response from the server request. Also the event is called too when the url is set to 'clientArray'.
- errorfunc: if defined, this function is called after the data is saved to the server. Parameters passed to this function are the rowid and the the response from the server request.
- afterrestorefunc if defined, this function is called in restoreRow (in case the row is not saved with success) method after restoring the row. To this function we pass the rowid
Except when url (or editurl) is 'clientArray', when this method is called, the data from the particular row is POSTED to the server in format name: value, where the name is a name from colModel and the value is the new value. jqGrid also adds, to the posted data, the pair id: rowid. For example,
jQuery("#grid_id").saveRow("rowid", false);
will save the data to the grid and to the server, while
jQuery("#grid_id").saveRow("rowid", false, 'clientArray');
will save the data to the grid without an ajax call to the server.
or using the new API
jQuery("#grid_id").jqGrid('saveRow',"rowid", false);
jQuery("#grid_id").jqGrid('saveRow',"rowid", false, 'clientArray');
Using the object parameter this should be written:
jQuery("#grid_id").jqGrid('saveRow',"rowid", { url : 'clientArray' });
Additionally to this we have other two options which can be set in grid options.
Property | Type | Description | Default |
---|---|---|---|
ajaxRowOptions | object | This option allow to set global ajax settings for the row editiing when we save the data to the server. Note that with this option is possible to overwrite all current ajax setting in the save request including the complete event. | empty object |
serializeRowData | postdata | If set this event can serialize the data passed to the ajax request when we save a row. The function should return the serialized data. This event can be used when a custom data should be passed to the server - e.g - JSON string, XML string and etc. To this event is passed the data which will be posted to the server | null |
restoreRow
This method restores the data to original values before the editing of the row.
Calling convention:
jQuery("#grid_id").restoreRow(rowid, afterrestorefunc);
or when we use the new API
jQuery("#grid_id").jqGrid('restoreRow',rowid, afterrestorefunc);
Calling with object parameter:
jQuery("#grid_id").jqGrid('restoreRow',rowid, { "afterrestorefunc" : function( response ) { // code here } });
The default object parameter is as follow:
restoreparameters = { "afterrestorefunc" : null } jQuery("#grid_id").jqGrid('restoreRow',rowid, restoreparameters);
where
- rowid is the row to restore
- afterrestorefunc if defined this function is called in after the row is restored. To this function we pas the rowid
addRow
This method add a row for inline edit.
Calling convention:
jQuery("#grid_id").addRow(rowid, parameters);
or when we use the new API
jQuery("#grid_id").jqGrid('addRow',parameters);
where parameters is a object and has the following default values:
parameters = { rowID : "new_row", initdata : {}, position :"first", useDefValues : false, useFormatter : false, addRowParams : {extraparam:{}} }
Where
- rowID - (string) the value of the id of the new added row
- initdata - (object) the object of the pair name:value where the name correspond to the name in colMode. When set this is the initial value of the the cell.
- position - (string) determines the position of the new adde row in the grid. Default is first. Can have a value last to be added at the last position
- useDefValues - (boolean) if set to true uses the defaultValue property in editoptions of the colModel
- useFormatter : (boolean) if set to true synchronises the parameters from the formatter actions
- addRowParams : (object) parameters which are passed to the addRow - they are the same as of editRow
Actually this method uses two already constructed methods. When calling the method first executes the addRowData method which add a local row. After this the method call editRow method to edit the row. If the keys parameter is set to true and the user press ESC key the row is automatically deleted.
inlineNav
Add a navigators buttons which correspond to the inline methods addRow, editRow, saveRow, restoreRow. In order to use this method a navGrid method should be called before to call this method
Calling convention:
jQuery("#grid_id").navGrid(pagerid, {...}); jQuery("#grid_id").inlineNav(pagerid, parameters);
or when we use the new API
jQuery("#grid_id").jqGrid('navGrid',pagerid, {...}); jQuery("#grid_id").jqGrid('inlineNav',pagerid, parameters);
Where parameters is a object with the following default values
parameters = { edit: true, editicon: "ui-icon-pencil", add: true, addicon:"ui-icon-plus", save: true, saveicon:"ui-icon-disk", cancel: true, cancelicon:"ui-icon-cancel", addParams : {useFormatter : false}, editParams : {} }
Property | Type | Description | Default1) |
---|---|---|---|
add | boolean | Enables or disables the add action in the Navigator. When the button is clicked a addRow with parameters addParams is executed | true |
addicon | string | Set a icon to be displayed if the add action is enabled. Note that currently only icons from UI theme images can be added | ui-icon-plus |
addtext | string | The text than can be set in the add button | empty |
addtitle | string | The title that appear when we mouse over to the add button (if enabled) | Add new row |
edit | boolean | Enables or disables the edit action in the Navigator. When the button is clicked a editRow method is executed with editParams parameter the - current selected row | true |
editicon | string | Set a icon to be displayed if the edit action is enabled. Note that currently only icons from UI theme images can be used | ui-icon-pencil |
edittext | string | The text than can be set in the edit button | empty |
edittitle | string | The title that appear when we mouse over to the edit button (if enabled) | Edit selected row |
position | string | Determines the position of the Navigator buttons in the pager. Can be left, center and right. | left |
save | boolean | Enables or disables the save button in the pager. When the button is clicked a saveRow method is executed with editParams parameters | true |
saveicon | string | Set a icon to be displayed if the refresh action is enabled. Note that currently only icons from UI theme images can be used | ui-icon-disk |
savetext | string | The text than can be set in the refresh button | empty |
savetitle | string | The title that appear when we mouse over to the refresh button (if enabled) | Save row |
cancel | boolean | Enables or disables the cancel(restore) button in the pager.When the button is clicked a restoreRow method is executed with parameters editParams | true |
cancelicon | string | Set a icon to be displayed if the search action is enabled. Note that currently only icons from UI theme images can be used | ui-icon-cancel |
canceltext | string | The text than can be set in the cancel button | empty |
canceltitle | string | The title that appear when we mouse over to the search button (if enabled) | Cancel trow editiong |
addParams | object | Parameters that can be passed to the addRow method in navigator. For detailed information see addRow parameters | {useFormatter : false} |
editParams | object | Parameters that can be passed to the editRow, saveRow, restoreRow methods in navigator. For detailed information the related methods | {} |
Notes
How is the data organized
When the row is edited and the input elements are created we set the following rules:
- the table row becomes attribute editable=“1”
- the array savedRow (option in the grid) is filled with the values before the editing. This is a name:value pair array with additional pair id:rowid
- Hidden fields are not included
- The id of the editable element is constructed as 'rowid_'+ the name from the colModel array. Example if we edit row with id=10 and the only editable element is 'myname' (from colModel) then the id becomes 10_myname.
- The name of the editable element is constructed from the name of the colModel array - property - name
- after the row is saved or restored the editable attribute is set to “0” and the savedRow item with id=rowid is deleted
What is posted to the server?
When the data is posted to the server we construct an object {} that contain(s):
- the name:value pair where the name is the name of the input element represented in the row (this is for all input elements)
- additionally we add a pair id:rowid where the rowid is the id of the row
- if the extraparam parameter is not empty we extend this data with the posted data
Example
... <head> <script type="text/javascript"> jQuery(document).ready(function(){ var lastsel2 jQuery("#rowed5").jqGrid({ datatype: "local", height: 250, colNames:['ID Number','Name', 'Stock', 'Ship via','Notes'], colModel:[ {name:'id',index:'id', width:90, sorttype:"int", editable: true}, {name:'name',index:'name', width:150,editable: true, editoptions:{size:"20",maxlength:"30"}}, {name:'stock',index:'stock', width:60, editable: true, edittype:"checkbox",editoptions: {value:"Yes:No"}}, {name:'ship',index:'ship', width:90, editable: true, edittype:"select",formatter:'select', editoptions:{value:"FE:FedEx;IN:InTime;TN:TNT;AR:ARAMEX"}}, {name:'note',index:'note', width:200, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"10"}} ], onSelectRow: function(id){ if(id && id!==lastsel2){ jQuery('#rowed5').restoreRow(lastsel2); jQuery('#rowed5').editRow(id,true); lastsel2=id; } }, editurl: "server.php", caption: "Input Types" }); var mydata2 = [ {id:"12345",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FE"}, {id:"23456",name:"Laptop",note:"Long text ",stock:"Yes",ship:"IN"}, {id:"34567",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TN"}, {id:"45678",name:"Speakers",note:"note",stock:"No",ship:"AR"}, {id:"56789",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FE"}, {id:"67890",name:"Play Station",note:"note3",stock:"No", ship:"FE"}, {id:"76543",name:"Mobile Telephone",note:"note",stock:"Yes",ship:"AR"}, {id:"87654",name:"Server",note:"note2",stock:"Yes",ship:"TN"}, {id:"98765",name:"Matrix Printer",note:"note3",stock:"No", ship:"FE"} ]; for(var i=0;i<mydata2.length;i++) jQuery("#rowed5").addRowData(mydata2[i].id,mydata2[i]); }); </script> </head> <body> <table id="rowed5" class="scroll"></table> </body> </html>
Discussion
Is it possible to have diff fields for form edit and inline edit in a same grid?
There is an escaping bug with special characters. Try insert <script>alert('hello')</script> into a field. It should be displayed as common text, but its executed. This is a common problem with inline editing.
Take a look at http://www.jstree.com/documentation/crrm (rename section)
Hi. I can't get editRow to eval the JSON in responseText. May there be an encoding issue? I've got something like
jQuery(”#tableId”).editRow(
);
Thanks
jQuery(”#tableId”).editRow( rowId, true, null, function(xhr) { var data = eval('(' + xhr.responseText + ')'); if(data.result == “success”) { jQuery(”#”+tableId).jqGrid('delRowData',rowId); } }, ajaxurl, postData );
Regards. Santiago
How is it possible to edit inline the grid without sending the data to the server, like shown on the example “Edit Row” (on the demo web site of trirand.com). The reason is that I have no PHP server and I want to save the grid locally.
And my second question: I wanted to serialize the grid data in a XML string: is it included in this plugin ?
Thanks, Pascal
After reading more carefully this page (sorry was too lazy …), I 've found the solution to save inside the grid only:
⇒> jQuery(”#grid_id”).saveRow(“rowid”, false, 'clientArray');
Data will not be posted to server. I am happy !!!
I'm using the jqgrid 4 development, so i want to colaborate with that project.
I found a problem with inline editing. jqgrid 4 sets focus by static value. So i'm using onCellSelect and just added an extra param to editRow method. So i did edit grid.inlinedir.js, adding focus on the parameters and removing the variable declaration 'focus=null'.
I did send the iCol param of onCellSelect by the focus param to the editRow method.
That is my code:
var lastsel; $(function(){ jQuery(”#rowed6”).jqGrid({ url:“listJSON”, editurl:“updateJSON”, datatype: “json”, height: 250, colNames:['Id','Data Inicial','Data final','Versão', 'Finalidade do Arquivo','codFin'], colModel:[ {name:'id',index:'id', width:90, sorttype:“int”}, {name:'dtIni',index:'dtIni',classes:'dtPicker',width:90,editable:true,sorttype:'date', editoptions:{ dataInit:function (elem) { $(elem).datepicker(); } }}, {name:'dtFin',index:'dtFin',classes:'dtPicker',width:90,editable:true,sorttype:'date', editoptions:{ dataInit:function (elem) { $(elem).datepicker(); } }}, {name:'codVer',index:'codVer',width:150,editable:true,editoptions:{size:“20”,maxlength:“30”}}, {name:'descCodVer',index:'descCodVer',width:150,editable:true,editoptions:{size:“20”,maxlength:“30”}}, {name:'codFin',index:'codFin',hidden: true} ], caption: “Date Picker Integration”, onCellSelect:function(rowid,iCol,cellcontent,e){ if(rowid && rowid!==lastsel){ jQuery('#rowed6').restoreRow(lastsel); lastsel=rowid; } jQuery('#rowed6').editRow(rowid, true,iCol); }, autowidth:true, rowNum:10, rowList:[10,20,30], pager: '#prowed3', sortname: 'id', viewrecords: true, sortorder: “asc” }); jQuery(”#rowed6”).jqGrid('navGrid',”#prowed3”,{edit:false,add:false,del:false}); });
grid.inlinedir.js line 13 -
editRow : function(rowid,keys,focus,oneditfunc,succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc)
line 35 -
var $t = this, nm, tmp, editable, cnt=0, svr={}, ind,cm;
It could be great if the data being edited do not change, then the data won't be saved to the server (that is the expected behaviour, I think ;) ).
Currently there is any way to do this?
There is a primitive solution to sort this problem at: http://stackoverflow.com/questions/6360512/jqgrid-inline-edit-detect-dirty-changed-cells/7141667
I'm a long-time fan of jqGrid and I hate to make my first official contact on the website a technical issue but this one has me really stumped (and I have rummaged through the documentation and searched all over the internets) …
I am using a jqGrid (latest version) in inline-edit mode to manage data completely on the client side (dataType is 'local'; I upload it to the server once the user is ready to move to the next phase). I use a OnSelectRow event to save the row being edited when you click on a different row. Both the editRow and saveRow methods in the event handler make a reference to 'clientArray'. editRow also uses keys = true (so I expect it to act accordingly on the Esc and Enter keys).
I am seeing this buggy behavior where pressing Enter only makes it “appear” that the data has been saved. The data in the underlying array (getGridParam('data')) is still unchanged. The only way data gets truly saved is when I click to a different row (and the OnSelectRow handler takes care of saving the row explicitly). Pressing Enter with keys = true (according to the source code) calls saveRow with rowId and “o” which appears to be the settings array starting with “keys”. Well, that would yield very different results given the saveRow method signature starts with “successfunc”. I have a feeling that this is causing the Enter-based saveRow to behave quite differently from the explicit saveRow in OnSelectRow because the parameter 'clientArray' is misaligned and the saveRow method treats it as some other sort of storage location (server-, url-based?). Any thoughts?
Thank you, all, in advance.
Tengo un problema con el dataInit reulta que deseo mostrar el formulario de editar y tengo dos campos fecha y quiero a ambos asignar el “datepicker”; lo asigna corectamente a ambos pero cuando deseo cambiar la fecha del segundo campo se pasa el foco al primer campo: Les dejo mi codigo…
jQuery(”#listado_es”).jqGrid({
Espero me puedan ayudar a solucionar este problema
Is there an easy way to check if the row is open for editing before acting on the key events. Currently I'm looping through RowIDs and comparing them and if it's the same then I save it.
Hi, i've found a small bug into the createEl function of grid.common.js (i use the 3.8.2 version but i see that is present in the 4.3.1 too). If i set a dataUrl for create a select element within inline editing, if the value (or text) of options contains html entity, in my case blank space ( ), when i click on row and go in edit mode the selected element not correspond with the option with the same text.
This occurs because this code checks for the text() or val() of an option into the value (ovm) (or values if multiselect) :
setTimeout(function(){ $(“option”,elem).each(function(i){ if(i===0) { this.selected = ””; } $(this).attr(“role”,”option”); if($.inArray($.trim($(this).text()),ovm) > -1 || $.inArray($.trim($(this).val()),ovm) > -1 ) { this.selected= “selected”; if(!msl) { return false; } } }); },0);
I solved adding the checks for the html() …so:Hope this help, Bye Gabriele
Haz lo siguiente:
Dentro de la funcion dataInit $(elemento_select).trigger('change') algo asi:
editoptions:{
}
I am having an issue with getting the keys (Esc and Enter) to work on a new record. Below is the code for my button:
$(”#t_clients”).append('<button type=“button” onclick=“$(\'#clients\').jqGrid(\'addRow\', {addRowParams: {extraparam: {keys: true}} });”>Add Client</button>');
According to the documentation, it seems like this should be working. Unfortunately, it doesn't. Any help would be greatly appreciated.
when using actions formatter (http://www.trirand.com/jqgridwiki/doku.php?id=wiki:predefined_formatter) restore rows like this
if(id && id!==lastsel2){ jQuery.fn.fmatter.rowactions(lastsel2,'rowed5','cancel',0); jQuery('#rowed5').editRow(id,true); lastsel2=id; }
instead of
if(id && id!==lastsel2){ jQuery('#rowed5').restoreRow(lastsel2); jQuery('#rowed5').editRow(id,true); lastsel2=id; }
It is more complete, not only restore row but restore edit buttons also. you can call the function using the onEdit event on colmodel.
;)
put formatter:'select' in select columns to get the value instead of text of the line