Friday, January 6, 2012

jqgrid - dynamic add/remove subgrid in run time

I'm using jqGrid 1.5.2, and I have a grid as subgrid, both parent and subgrid are in cell edit mode with no sorting allow.

In loadComplete event of the parent grid, I successful removed some of the subgrids which depended on the data of the row by unbind event to the element as following:

loadComplete: function() {
  var dataIds = $('#mygrid1').jqGrid('getDataIDs');
  for (var i = 0;i < dataIds.length; i++) {
    var data = $("#mygrid1").jqGrid('getRowData', dataIds[i]);
    if (data[i].hasChild='N') {
      var grid = $("#mygrid1");      
      currChild[dataIds[i]=$( "#"+dataIds[i]+"td.sgcollapsed",grid[0].clone(true,ture); //Before unbind, store up the event and data of the element in an array for dynamically added back
      $("#"+dataIds[i]+"td.sgcollapsed",grid[0]).unbind('click').html(''); //then, it's safe to remove 
    } 
} }

Then, I allow user to change the data[i].hasChild in the parent gird, then I call this dynamically change in afterSaveCell event as follow:

if (change/toggle happened) {
var grid = $("#mygrid1"); 
  if (data[rowid].hasChild=='Y') {
   $("#"+rowid+" td.sgcollapsed", grid[0].replaceWith(currChild[rowid]); //replace the element with the clone
  } else {
    grid.collapseSubGridRow(rowid); //require to collapse the subgrid before remove
    currChild[rowid]=$("#"+rowid+"td.sgcollapsed",grid[0].clone(true,ture); //Before unbind, store up the event and data of the element again in its array
    $( "#"+rowid+"td.sgcollapsed",grid[0]).unbind('click').html(''); //then, it's safe to unbind again
}}

No comments: