How can I make to show the subgrids from JQgrid by default? - jqgrid

TypeError: this.each is not a function
return this.each(function () {this is my code from the subgrid sequence:
subGrid : true,
subGridRowExpanded: function(subgrid_id, row_id) {
//var projectIdRow = $('#list2').jqGrid('getCell',rowId,'projectid');
var subgrid_table_id;
subgrid_table_id = subgrid_id+"_t";
$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"'></table>");
$("#"+subgrid_table_id).jqGrid({
url:"/taskuri/subGrid/?id="+row_id,
datatype: "json",
colNames: ['SubTask',' ','Pri','Responsabil','Alocator','Alocat','Deadline','Estimat','Lucrat',' '],
colModel: [
{name:"SubTask",index:"SubTask",width:'687%',align:"left",sortable:false},
{name:'finished',index:'finished', width:'40%',sortable:false},
{name:"Pri",index:"Pri",width:'56%', sortable:true},
{name:"Responsabil",index:"Responsabil",width:'128%',sortable:false},
{name:"Alocator",index:"Alocator",width:'130%',sortable:false},
{name:"Alocat",index:"Alocat",width:'110%',sortable:false},
{name:"Deadline",index:"Deadline",width:'110%',sortable:false},
{name:"Estimat",index:"Estimat",width:'76%',align:"right",sortable:false},
{name:"Lucrat",index:"Lucrat",width:'90%',align:"right"},
{name:"Delete",index:"Delete",width:'90%',align:"right"},
],
height: '100%',
rowNum:20,
});
},
I want to things. Firstly to show the subgrid by default(when i access the page). Secondly to no dot displays the subgrid if there is no data there. How can I do that? Below I upload an image to see how it displays, if if there is no data. thx
I tried this method :
gridComplete: function(){
var grid = $("#list2");
var svi_id = grid.jqGrid('getDataIDs');
$.each(svi_id, function (index, rowId) {
$(this).jqGrid.expandSubGridRow(rowId);
// or grid.jqGrid.expandSubGridRow(rowId);
});
},
and the result is an error : TypeError: this.each is not a function
return this.each(function () { { (firebug). What is wrong ?

this is the right code to display by default the subgrids
gridComplete: function(){
var grid = $("#list2");
var svi_id = grid.jqGrid('getDataIDs');
$.each(svi_id, function (index, rowId) {
grid.jqGrid('expandSubGridRow',rowId);
});
},

Check for expandSubGridRow.... you can do this in your loadcomplete of the parent grid !!
loadComplete: function () {
var timeOut = 50;
var rowIds = $("#list").getDataIDs();
$.each(rowIds, function (index, rowId) {
setTimeout(function () {
$("#list").expandSubGridRow(rowId);
}, timeOut);
timeOut = timeOut + 200;
});
}

Related

Borwser's back button state update after ajax call

I am trying to sort out back and forward browser buttons in my ajax page load setup.
This is my ajax code that calls page content:
jQuery(document).ready(function () {
$ = jQuery;
$("body").on("click", ".menuAjax a", function (e) {
//On click on body for ajax calls
e.preventDefault();
var pageID = $(this).data("id");
var catType = $(this).data("type");
var pageTitle = $(this).data("title");
var footerAdSwitch = $("#overFooter").data("footeradswitch");
var homePageSet = parseInt($("#homePageSet").val());
var $this = $(this);
//console.log($this);
var res;
var payload = JSON.stringify({
action: "router_loader",
pageid: pageID,
footeradswitch: footerAdSwitch,
homepage: homePageSet,
cattype: catType,
pagetitle: pageTitle,
});
XHR = $.ajax({
type: "get",
url: my_ajax_object.ajax_url + '/' + payload + '/view_' + (pageID || catType),
beforeSend: function () {
$("#ajaxPageLoader").show();
},
complete: function () {
$("#ajaxPageLoader").hide();
},
success: function (res) {
if (res != "") {
$("#ajaxpageLoad").html(res);
setTimeout(function () {
$("#ajaxPageLoader").hide();
}, 600);
$(".nav li.menu-item").removeClass(
"current-menu-item current_page_item"
);
$($this).parent().addClass("current-menu-item current_page_item");
const nextURL = $this[0].href;
history.pushState(res, pageTitle, nextURL);
document.title = pageTitle + " - company name";
$.getScript("/wp-content/themes/customTpl/js/functions.js");
var lazyLoadInstance = new LazyLoad({
threshold: 200,
});
$("html, body").animate({ scrollTop: 0 }, 0);
} else {
$("#ajaxPageLoader").hide();
}
},
error: function (req, status, error) {},
});
});
//Exclude expander btn from ajax call
$("body").on("click", ".btnNoBorder, .mobileMenueBtn, .closeBtn", function (e) {
e.stopPropagation();
});
window.addEventListener('popstate', function(e) {
$("#ajaxpageLoad").html(res);
updateContent(e.state);
});
});
Right now I ma stuck with popstate function, which I would like to pass urls of current position, so they are remembered once a users presses back button.
Can someone suggest me direction as to how to update history navigation with the browser buttons ?

HandsonTable AfterUpdate (OpenSource Version)

There seem to be two versions of the "Handsontable is a simple jQuery plugin for editable tables with basic copy-paste compatibility with Excel and Google Docs" So this question is about the open source (MIT) version, Handsontable 0.11.4. I am using selenium, I was able to add IDs to the cells using the code below. And I can add data to the table using selenium by.id. But then the afterChange is not called. Any tips on how to automatically trigger the afterChange event to get the ajax call to run in my code below?
function myRenderer(instance, td, row, col, prop, value, cellProperties) {
Handsontable.renderers.TextRenderer.apply(this, arguments);
td.setAttribute("id", "db<c:out value="${loopStatus.index}" />-row-"+row+"-"+"col"+col);
}
var $console<c:out value="${loopStatus.index}" /> = $("#colors_status<c:out value="${loopStatus.index}" />");
var autosave_notification<c:out value="${loopStatus.index}" />;
var data<c:out value="${loopStatus.index}" /> = ${oi.decorationBlock.colorSequenceDO.colors}
$("#colors<c:out value="${loopStatus.index}" />").handsontable({
data: data<c:out value="${loopStatus.index}" />,
minRows: ${oi.decorationBlock.colorSequenceDO.hotStartRows},
minCols: ${oi.decorationBlock.colorSequenceDO.hotStartCols},
colHeaders: ${oi.decorationBlock.colorSequenceDO.columnHeaders},
colWidths: [180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180],
manualColumnResize: true,
rowHeaders: true,
fixedColumnsLeft: 0,
minSpareRows: 1,
columns: [
${refData.autocomplete_colors}
],
afterChange: function (change, source) {
if (source === 'loadData') {
return; //don't save this change
}
clearTimeout(autosave_notification<c:out value="${loopStatus.index}" />);
$.ajax({
url: "save_colors.html?orderid=${command.order.id}&DBID=<c:out value="${oi.decorationBlock.id}" />",
dataType: "json",
contentType: "application/json",
type: "POST",
processData: false,
data: JSON.stringify({ColorAction: change}), //contains changed cells' data
complete: function (data) {
$console<c:out value="${loopStatus.index}" />.text('saving...');
autosave_notification<c:out value="${loopStatus.index}" /> = setTimeout(function () {
$console<c:out value="${loopStatus.index}" />.text('saved');
}, 1000);
}
});
}
});
var hotInstance = $("#colors<c:out value="${loopStatus.index}" />").handsontable('getInstance');
hotInstance.updateSettings({
cells: function(row, col, prop) {
var cellProperties = {};
cellProperties.renderer = myRenderer;
return cellProperties;
}
});

What causes jqgrid events to fire multiple times?

Our jqgrid is configured in an initgrid function that is called as the last statement of a ready handler. For some reason, the gridcomplete function is getting called multiple times. With the code below, it gets called twice, but it had been getting called 3 times. Twice is bad enough. After stepping through it multiple times, I don't see what is triggering the second execution of the gridComplete function.
When I hit the debugger at the start of gridComplete, the call stack is virtually identical each time, the only difference being a call to 'L' in the jqgrid:
Anyone have an idea why this is occurring? We are using the free version 4.13, in an ASP.net MVC application.
$(function(){
....
initGrid();
}
function initGrid(){
$gridEl.jqGrid({
xhrFields: {
cors: false
},
url: "/IAConsult/GetWorkFlowIARequests",
postData: {
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
datatype: "json",
crossDomain: true,
loadonce: true,
mtype: 'GET',
sortable: true,
viewrecords: true,
pager: '#workFlowIAGridPager',
multiselect: true,
rowNum: 50,
autowidth: true,
colModel: [...],
beforeSelectRow: function (rowid, e) {
var $myGrid = $(this),
i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
cm = $myGrid.jqGrid('getGridParam', 'colModel');
return (cm[i].name === 'cb');
},
jsonReader: {
repeatitems: true,
root: "IAConsultWorkflowRequestsList"
},
beforeSubmitCell: function (rowid, name, value, iRow, iCol) {
return {
gridData: gridData
};
},
serializeCellData: function (postdata) {
return JSON.stringify(postdata);
},
gridComplete: function () {
console.log('grid complete');
let rowIDs = $gridEl.getDataIDs();
let inCompleteFlag = false;
let dataToFilter = $gridEl.jqGrid('getGridParam', 'lastSelectedData').length == 0
? $gridEl.jqGrid("getGridParam", "data")
: $gridEl.jqGrid('getGridParam', 'lastSelectedData');
let $grid = $gridEl, postfilt = "";
let localFilter = $gridEl.jqGrid('getGridParam', 'postData').filters;
let columnNames = columns.split(',');
$('.moreItems').on('click', function () {
$.modalAlert({
body: $(this).data('allitems'),
buttons: {
dismiss: {
caption: 'Close'
}
},
title: 'Design Participants'
});
});
rowCount = $gridEl.getGridParam('records');
gridViewRowCount = rowCount;
let getUniqueNames = function (columnName) {
... };
let buildSearchSelect = function (uniqueNames) {
var values = {};
values[''] = 'All';
$.each(uniqueNames,
function () {
values[this] = this;
});
return values;
};
let setSearchSelect = function (columnName) {
...
};
function getSortOptionsByColName(colName) {
...
}
$grid.jqGrid("filterToolbar",
{ stringResult: true, searchOnEnter: true });
if (localFilter !== "" && localFilter != undefined) {
globalFilter = localFilter;
}
let grid = $gridEl.jqGrid("setGridParam",
{
postData: {
"filters": globalFilter,
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
search: true,
forceClientSorting: true
});
//grid.trigger("reloadGrid");
//Ending Filter code
for (i = 0; i < columnNames.length; i++) {
var htmlForSelect = '<option value="">All</option>';
var un = getUniqueNames(columnNames[i]);
var $select = $("select[id='gs_workFlowIAGrid_" + columnNames[i] + "']");
for (j = 0; j < un.length; j++) {
val = un[j];
htmlForSelect += '<option value="' + val + '">' + val + '</option>';
}
$select.find('option').remove().end().append(htmlForSelect);
}
debugger;
},
// all grid parameters and additionally the following
loadComplete: function () {
$gridEl.jqGrid('setGridWidth', $(window).width(), true);
$gridEl.setGridWidth(window.innerWidth - 20);
},
height: '100%'
});
I personally almost never use gridComplete callback. It exists in free jqGrid mostly for backwards compatibility. I'd recommend you to read the old answer, which describes differences between gridComplete and loadComplete.
Some additional advices: it's dangerous to register events inside of callbacks (see $('.moreItems').on('click', ...). If you need to make some actions on click inside of grid then I'd recommend you to use beforeSelectRow. Many events, inclusive click event supports event bubbling and non-handled click inside of grid will be bubbled to the parent <table> element. You use already beforeSelectRow callback and e.target gives you full information about clicked element.
I recommend you additionally don't use setGridParam method, which can decrease performance. setGridParam method make by default deep copy of all internals parameters, inclusive arrays like data, which can be large. In the way, changing one small parameter with respect of setGridParam can be expensive. If you need to modify a parameter of jqGrid then you can use getGridParam without additional parameters to get reference to internal object, which contains all jqGrid parameters. After that you can access to read or modify parameters of jqGrid using the parameter object. See the answer for example for small code example.
Also adding the property
loadonce: true
might help.

JQgrid custom button to display additional record details as in view record dialog

Here is my code for custom button, i would like to display additional details about the selected row from server side to jqgrid dialog box with similar look and feel of view record dialog. Can someone help with a sample code to create a dialog box similar to view record from custom button onclick?
jQuery("#list2").jqGrid('navButtonAdd','#pager2',{
caption:"", title: "History",buttonicon:"ui-icon-clock",
onClickButton : function () {
var grid = $("#list2");
var rowid = grid.jqGrid('getGridParam', 'selrow');
if (rowid) {
var alertIDs = {themodal:'alertmod',modalhead:'alerthd',modalcontent:'alertcnt'};
//if ($("#"+alertIDs.themodal).html() === null) {
//alert("1");
$.jgrid.createModal(alertIDs," <span tabindex='0'><span tabindex='-1' id='jqg_alrt' class='ui-jqgrid'></span></span>",
{gbox:"#gbox_"+$.jgrid.jqID(this.p.id),jqModal:true,drag:true,resize:true,
caption:"History",
top:300,left:500,width:'auto',height: 'auto',closeOnEscape:true,
zIndex: null},"","",true);
$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID(this.p.id),jqm:true});
$("#jqg_alrt").focus();
$("#jqg_alrt").load('jsontableHeadingsApartmentResource.action?viewBy=' + viewBy+'&timeZone=' + timeZone);
} else {
var alertIDs = {themodal:'alertmod',modalhead:'alerthd',modalcontent:'alertcnt'};
$.jgrid.createModal(alertIDs,"<div>"+$.jgrid.nav.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",
{gbox:"#gbox_"+$.jgrid.jqID(this.p.id),jqModal:true,drag:true,resize:true,
caption:$.jgrid.nav.alertcap,
top:300,left:500,width:200,height: 'auto',closeOnEscape:true,
zIndex: null},"","",true);
$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID(this.p.id),jqm:true});
$("#jqg_alrt").focus();
}
}
});
Found the solution.
Here is the updated working code, i had to use jgrid info_dialog,
jQuery("#list2").jqGrid('navButtonAdd','#pager2',{
caption:"", title: "History",buttonicon:"ui-icon-clock",
onClickButton : function () {
var grid = $("#list2");
var rowid = grid.jqGrid('getGridParam', 'selrow');
var msg = "" ;
if (rowid) {
$.ajax({
url: 'jsontableHistoryApartmentResource.action?viewBy=' + viewBy+'&rowId=' + rowid,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, st) {
if (st == "success") {
msg = data.rr.history;//jqgrid history data
$.jgrid.info_dialog('History','<span style="white-space: nowrap">' + msg +'</span>', $.jgrid.edit.bClose,{buttonalign:'center', width:'auto',resize: true , align: 'left'});
}
},
error: function () {
// alert("Error with AJAX callback");
}
});
} else {
var alertIDs = {themodal:'alertmod',modalhead:'alerthd',modalcontent:'alertcnt'};
$.jgrid.createModal(alertIDs,"<div>"+$.jgrid.nav.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",
{gbox:"#gbox_"+$.jgrid.jqID(this.p.id),jqModal:true,drag:true,resize:true,
caption:$.jgrid.nav.alertcap,
top:300,left:500,width:200,height: 'auto',closeOnEscape:true,
zIndex: null},"","",true);
$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID(this.p.id),jqm:true});
$("#jqg_alrt").focus();
}
}
});

jqGrid change dynamically edittype for specific row

Following to this post where I found some way to do that I would want to get, I meet some trouble with it.
Here is my code :
var myDlg = $("#dlgpers"),lastsel;
myDlg.jqGrid({
url:'pers.php?id='+dataRow.id,
mtype:'GET',
datatype: "json",
ajaxGridOptions: { cache: false },
height:250,
cmTemplate: {sortable:false},
gridview: true,
cellEdit:true,
scroll:false,
colNames:['Id','Label','Information','Type','Data'],
colModel:[
{name:'id',index:'id',hidden:true,key:true},
{name:'label',index:'label',align:'right',width:100,editable:false,
cellattr: function (rowId, val, rawObject, cm, rdata) {
return ' style="font-weight:bold;margin-right:5px;border-left:0;border-top:0;" class="ui-state-active"' ;
}
},
{name:'info',index:'info',width:200,editable:true,edittype:'text'},
{name:'type',index:'type',width:30,hidden:true},
{name:'data',index:'data',width:30,hidden:true}
],
loadComplete: function () {
var rowIds = myDlg.jqGrid('getDataIDs');
$.each(rowIds, function (i, row) {
var rowData = myDlg.jqGrid('getRowData',row);
if (rowData.type == 'select') {
myDlg.jqGrid('restoreRow', row);
var cm = myDlg.jqGrid('getColProp', 'info');
cm.edittype = 'select';
cm.editoptions = { value: rowData.data };
myDlg.jqGrid('editRow', row);
cm.edittype = 'text';
cm.editoptions = null;
cm.editable = true;
}else{
myDlg.jqGrid('restoreRow', row);
var cm = myDlg.jqGrid('getColProp', 'info');
cm.edittype = 'text';
cm.editoptions = null;
cm.editable = true;
myDlg.jqGrid('editRow', row);
cm.edittype = 'text';
cm.editoptions = null;
cm.editable = true;
}
});
}
});
and the result as image :
and the JSON response :
{"page":1,"total":1,"records":1,"rows":[
{"cell":[0,"Nom ","LEBRUN","text",""]},
{"cell":[1,"Pr\u00e9nom ","Jacques","text",""]},
{"cell":[2,"Initiales ","LJ","text",""]},
{"cell":[3,"Fonction ","","text",""]},
{"cell"[4,"Service,"Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
{"cell":[5,"T\u00e9l\u00e9phone ","","text",""]},
{"cell":[6,"Email ","","text",""]},
{"cell":[7,"Statut ","CDI","select","0:CDI;1:CDD;2:App;3:Stg;4:Int"]},
{"cell":[8,"Entr\u00e9 le ","2008-10-06","text",""]},
{"cell":[9,"Sorti le ","0000-00-00","text",""]}]}
Two questions I submit to your knowledge:
As you can see, the second line (Prénom) don't seem editable, but it is.
I don't understand why these inputs are visible, as I would want they appear only if I edit some cell.
Many thanks for all your kind help for resolve (and explain) my wrong way.
JiheL
UPDATED 2013-03-29
I have applied your answer code and that run fine ! Many thanks.
But I have created another form in such a way for another subject, and that cause me some troubles.
Here is the code of this new form :
var showAbs=function(){
$('#EditDialog').empty();
var $table=$('<table></table>')
.attr('id','dlgcong')
.appendTo($('#EditDialog'));
var myCong = $("#dlgcong");
myCong.jqGrid({
url:'xpabs.php?id='+id+'&y='+y,
datatype: "json",
height:"auto",
cmTemplate: {sortable:false},
gridview: true,
colNames:['Type absence','Début','Fin','id'],
colModel:[
{name:'abs',index:'abs',width:155,editable:true,edittype:'select',
editoptions:{
dataUrl:"selabs.php",
dataEvents: [
{
type: 'change',
fn: function(e) {
$(this).parent().css('background-color','#'+$(this).find('option:selected').attr('colr'));
if($(this).find('option:selected').attr('colr')=='ffffff'){
$(this).parent().parent().find('input').datepicker('disable');
}else{
$(this).parent().parent().find('input').datepicker('enable');
$(this).parent().parent().attr('changed',true);
}
}
}
]
},
cellattr: function (rowId, val, rawObject, cm, rdata) {
return ' style="background-color:#'+rawObject[4]+';color:white;"';
}
},
{name:'debut',index:'debut',align:'center',width:70,editable:true},
{name:'fin',index:'fin',align:'center',width:70,editable:true},
{name:'id',index:'id',hidden:true}
],
jsonReader: {
cell: "",
root: function (obj) {
return obj;
}
},
loadComplete: function (data) {
var $self = $(this),
cm = $self.jqGrid("getColProp", "debut"),
idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
l = data.length,
i,
item;
for (i = 0; i < l; i++) {
item = data[i];
cm.editoptions = {
dataInit: function(element) {
$(element).datepicker({
setDate:item[1],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
}
}
var cm = $self.jqGrid("getColProp", "fin");
for (i = 0; i < l; i++) {
item = data[i];
cm.editoptions = {
dataInit: function(element) {
$(element).datepicker({
setDate:item[2],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
}
$self.jqGrid("editRow", idPrefix + item[3]);
}
myCong.find('select').each(function(){
$(this).css({
backgroundColor:'transparent',
color:'white',
border:0,
width:155
});
});
},
idPrefix: "cong",
rowNum: 10000
});
//********************
// Button ' Valider '
//********************
$('<input />')
.attr({
type:'button',
})
.css({
float:'right',
marginTop:'5px'
})
.click(function(){
var toBeSaved='';
myCong.find('tr[changed=true]').each(function(idx){
if(toBeSaved.length>0){
toBeSaved+='|';
}
toBeSaved+=$(this).find('td:eq(3)').text()+';';
toBeSaved+=$(this).find('select option:selected').val()+';';
toBeSaved+=$(this).find('input:eq(0)').val()+';';
toBeSaved+=$(this).find('input:eq(1)').val();
});
if(toBeSaved.length>0){
$.ajax({
url:'majpabs.php?id='+id+'&data='+toBeSaved,
async:false,
dataType:'json',
success:function(data){
myGrid.trigger('reloadGrid');
$('#newAbs').val(' Nouveau ').attr('disabled',false);
}
});
}
})
.val(' Valider les absences ')
.appendTo($('#EditDialog'));
//*******************
// Button ' Retour '
//*******************
$('<input />')
.attr({
type:'button',
id:'newAbs'
})
.css({
float:'left',
marginTop:'5px'
})
.click(function(){
showPers();
})
.val(' Retour ')
.appendTo($('#EditDialog'));
//********************
// Button ' Nouveau '
//********************
$('<input />')
.attr({
type:'button',
disabled:false
})
.css({
float:'left',
marginTop:'5px',
marginLeft:'7px'
})
.click(function(){
if($(this).val()==' Nouveau '){
var myRow = {abs:"0", debut:'00/00/'+y, fin:'00/00/'+y, id:'0'};
myCong.jqGrid('addRowData','',myRow, 'last');
$(this).val(' Sauver ').attr('disabled',true);
}else{
}
})
.val(' Nouveau ')
.appendTo($('#EditDialog'));
}
and the result as image :
As you can see, the first row does not receive select and datepicker as other rows. Strange !
When I add new row, it does not receive select and datepicker as the first row.
I think I'm wrong in understanding this method.
I'm worry to bother you with these questions, I had a look in wiki without success to find any way to make these points correct. I would like to find some more detailed tutorial which show some cases examples.
Thank you VERY MUCH if you can spend again some time for give me a way to be more efficient with jqGrid.JiheL
UPDATED 2013-04-01
I have applied Oleg's suggestions and that works now. But a trouble remains.
here is the image :
For the first row, select box is OK.
The first input field receive datepicker, but the second (the column called 'fin') not !
All others rows receive well datepickers, but not the last field of first row.
Here is the code :
loadComplete: function (data) {
var $self = $(this),
idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
l = data.length,
i,
item,
cm;
for (i = 0; i < l; i++) {
item = data[i];
cm = $self.jqGrid("getColProp", "debut");
cm.editoptions = {
dataInit: function(element) {
//alert('deb'+i);
$(element).datepicker({
setDate:item[1],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
};
$self.jqGrid("editRow", idPrefix + item[3]);
//
cm = $self.jqGrid("getColProp", "fin");
cm.editoptions = {
dataInit: function(element) {
//alert('fin'+i);
$(element).datepicker({
setDate:item[2],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
};
$self.jqGrid("editRow", idPrefix + item[3]);
}
myCong.find('select').each(function(){
$(this).css({
backgroundColor:'transparent',
color:'white',
border:0,
width:155
});
});
},
Another time, I hope you can help me to resolve this trouble and close this request.
Many thanks for all the time you spend to help newbies.
JiheL
I think that many from the problems in your code common. So I tried to answer on you question more detailed.
First of all you posted wrong JSON data. The line
{"cell"[4,"Service,"Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
contains two errors:
no ':' after "cell"
no " after "Service
After the changes the line will be so
{"cell":[4,"Service","Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
and JSON data could be read. The next problem is the usage of numbers together with string in one array. Because the bug in the line of jqGrid code
idr = ccur !== undefined ? ccur[idn] || idr : idr;
ids could not be integer value 0. I posted the bug report about the error. To fix the problem using existing code of jqGrid you should use strings instead of numbers. For example the line
{"cell":[0,"Nom ","LEBRUN","text",""]},
should be changed to
{"cell":["0","Nom ","LEBRUN","text",""]},
Without the changes you will have id duplicates. Both first lines ({"cell":[0,"Nom ","LEBRUN","text",""]} and {"cell":[1,"Pr\u00e9nom ","Jacques","text",""]},) will get the same id equal to 1 instead of 0 and 1. It was the main reason of the problem which you described.
Additionally I would recommend you the following:
remove cellEdit:true option. You use editRow later in the code. It means that you use inline editing instead of cell editing which means cellEdit:true. You can't combine both editing modes in one grid.
replace height:250 option to height:"auto"
remove all index properties from colModel. Remove all properties of colModel with default values (edittype:'text', editable:false)
remove options of jqGrid with default values (mtype:'GET', scroll:false)
all parameters of functions in JavaScript are optional. So if you don't use for example any parameters of cellattr callback you can replace cellattr: function (rowId, val, rawObject, cm, rdata) {...} to cellattr: function () {...}
the callback loadComplete has one parameter data which can provide you all data which returned from the server. So you don't need to use getDataIDs and getRowData. The array data.rows can by directly used.
if you use data parameter of loadComplete callback you can remove unneeded 'type' and 'data' columns from the grid.
if you place information about id after 'Label','Information' then you can use id property of jsonReader and remove hidden id column from the grid too. For example if you move id as the last in the cell array you can use jsonReader: {id: 4} and remove hidden id column from the grid. If you add additionally cell: "" property in jsonReader you can remove "cell": from the input data. If you would use root property of jsonReader defined as function (see the documentation) you can remove some unneeded data from the server response.
For example the server can produce the simplified data
[
["Nom ","LEBRUN","text","","0"],
["Pr\u00e9nom ","Jacques","text","","1"],
["Initiales ","LJ","text","","2"],
["Fonction ","","text","","3"],
["Service","Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests","4"],
["T\u00e9l\u00e9phone ","","text","","5"],
["Email ","","text","","6"],
["Statut ","CDI","select","0:CDI;1:CDD;2:App;3:Stg;4:Int","7"],
["Entr\u00e9 le ","2008-10-06","text","","8"],
["Sorti le ","0000-00-00","text","","9"]
]
The corresponding jqGrid could be
$("#dlgpers").jqGrid({
url: "pers.php?id=" + dataRow.id,
datatype: "json",
height: "auto",
cmTemplate: {sortable: false},
gridview: true,
colNames: ["Label", "Information"],
colModel: [
{name: "label", align: "right", width: 100,
cellattr: function () {
return ' style="font-weight:bold;margin-right:5px;border-left:0;border-top:0;" class="ui-state-active"';
}},
{name: "info", width: 200, editable: true}
],
jsonReader: {id: 4, cell: "", root: function (obj) { return obj; } },
loadComplete: function (data) {
var $self = $(this),
cm = $self.jqGrid("getColProp", "info"),
idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
l = data.length,
i,
item;
for (i = 0; i < l; i++) {
item = data[i];
cm.edittype = item[2] === "select" ? "select" : "text";
cm.editoptions = { value: item[3] };
$self.jqGrid("editRow", idPrefix + item[4]);
}
},
idPrefix: "dlg",
rowNum: 10000 // to have no paging
});
See the demo:

Resources