Refers to: jqgrid: how to set toolbar options based on column value in row selected - jqgrid

my question refers to http://goo.gl/f0Boc
The code works fine for me, but now I want to enable/disable the "Edit-Button" when the value in a cell is "Yes" or "No".
In this example is written:
// you can use getCell or getRowData to examine the contain of
// the selected row to decide whether the row is editable or not
I need an explanation how I could change the code so that the code runs with jqGrid('getCell',rowid,'cellContent')?
What I need is if cellContent is "Yes" then disable "Edit-Button".
Thanks in advance for your efforts,
best regards
Stephan
<script type="text/javascript">
$(function(){
$("#list").jqGrid({
url:'example.php',
datatype: 'xml',
mtype: 'GET',
colNames:['User ID','Name', 'Firstname','CDS-ID','E-mail','Password', 'Registration
Date','Account Activated', 'Account Activation Date', 'Role'],
colModel :[
{name:'idUser_registration', index:'idUser_registration', width:55,
editable:true, editoptions{readonly:true},search:true},
...
{name:'account_activated', index:'account_activated', width:150, align:'right',
edittype:'checkbox',editoptions: { value:"Yes:No" }, editable:true,
search:true},
... ],
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'idUser_registration',
sortorder: 'asc',
viewrecords: true,
gridview: true,
caption: 'My grid',
editurl: 'example2.php',
beforeSelectRow: function(rowid) {
var selRowId = $(this).getGridParam('selrow'),
celValue = $(this).getCell('getCell', selRowId, 'list_account_activated'),
tr = $("#"+rowid);
// you can use getCell or getRowData to examine the contain of
// the selected row to decide whether the row is editable or not
if (selRowId !== rowid && !tr.hasClass('not-editable-row')) {
// eneble the "Edit" button in the navigator
$("#edit_" + this.id).removeClass('ui-state-disabled');
$("#del_" + this.id).removeClass('ui-state-disabled');
}
else {
// unselect previous selected row
// disable the "Edit" and "Del" button in the navigator
$("#edit_" + this.id).addClass('ui-state-disabled');
$("#del_" + this.id).addClass('ui-state-disabled');
}
return true; // allow selection or unselection
},
loadComplete: function() {
// just one example how to mark some rows as non-editable is to add
// some class like 'not-editable-row' which we test in beforeSelectRow
$("tr.jqgrow:even",this).addClass('not-editable-row');
}
}).jqGrid('navGrid','#pager',
{}, //options
{closeAfterEdit:true,mtype:'GET',editCaption: "Activate
Account",height:400,reloadAfterSubmit:true },
{reloadAfterSubmit:false}, // del options
{} // search options
);
$("#edit_").click(function() {
var gr = jQuery("#list").jqGrid('getGridParam','selrow');
if( gr != null ) jQuery("#list").jqGrid('editGridRow',gr,{});
});
$("#del_").click(function(){
var gr = jQuery("#list").jqGrid('getGridParam','selrow');
if( gr != null ) jQuery("#list").jqGrid('delGridRow',gr,{mtype:'GET',reloadAfterSubmit:true});
});
});
</script>

I modified the referenced demo for you. The main part of the code is the following
onSelectRow: function (rowid) {
var thisId = $.jgrid.jqID(this.id),
isCompleted = $(this).jqGrid("getCell", rowid, "isCompleted");
// you can use getCell or getRowData to examine the contain of
// the selected row to decide whether the row is editable or not
if (isCompleted !== "Yes") {
// eneble the "Edit" button in the navigator
$("#edit_" + thisId).removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
} else {
// unselect previous selected row
// disable the "Edit" and "Del" button in the navigator
$("#edit_" + thisId).addClass('ui-state-disabled');
$("#del_" + thisId).addClass('ui-state-disabled');
}
}
You can see new demo here.

Related

Which event gets fired when delete row occurs?

Grid contains after save row event "jqGridInlineAfterSaveRow" which works if you edit or add row.
//--Bind events...
console.log('Bind events...');
$("#jqGrid").bind("jqGridInlineAfterSaveRow",function (e, rowid, jqXhrOrBool, postData, options) {
console.log('EVENT:jqGridInlineAfterSaveRow');
var item = $(this).jqGrid('getLocalRow', rowid);
console.log(item);
console.log('BEFORE:');
saveObject(item);
console.log('AFTER:');
});
What is name of the event for delete row? i need to bind my JS function for delete row.
UPDATE 1
I am trying following option now, but no luck...
}).jqGrid("navGrid", "#jqGridPager", {edit: false, add: false, del: false, refresh: false, view: false,search: false,
delfunc: function (rowids) {
console.log(rowids);
}
})
UPDATE 2
I think issue is with delete buttons at row level not at footer
see the screenshot [enter image description here][1]
data:rdata,
colModel: [
{
label: "",
name: "",
width: 70,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: { delfunc : function (id){
console.log(">>>>>>>>>>>>>>>>1");
}}
}
},
UPDATE 3
Based on Oleg's input, i have changed the code as following:
$("#jqGrid").bind("jqGridAfterDelRow",function (e, rowid, jqXhrOrBool, postData, options) {
console.log('EVENT:jqGridAfterDelRow');
console.log(rowid);
var item = $(this).jqGrid('delRowData ', rowid);
console.log(item);
console.log('BEFORE:');
console.log('AFTER:');
});
But now, i am not getting deleted row object??? Actually, i need to get the some of the fields from deleted row e.g. ID. and above binding function will in turn call server side ajax function.
UPDATE 4
Thanks to Oleg for supporting beyond... Here is the code i have mashup from one of the answers from him.
colModel: [
{
label: "",
name: "",
width: 70,
formatter: "actions",
formatoptions: {
keys: true,
editbutton : true,
delbutton : true,
editOptions: {},
addOptions: {},
delOptions: {
onclickSubmit: function(options, rowid) {
console.log("delOptions::onclickSubmit");
var grid_id = $.jgrid.jqID(grid[0].id);
var grid_p = grid[0].p;
var newPage = grid[0].p.page;
var rowdata = grid.getLocalRow(rowid);
// DELETE GRID LOCAL ROW
grid.delRowData(rowid);
$.jgrid.hideModal("#delmod"+grid_id,
{gb:"#gbox_"+grid_id,jqm:options.jqModal,onClose:options.onClose});
if (grid_p.lastpage > 1) {// on the multipage grid reload the grid
if (grid_p.reccount === 0 && newPage === grid_p.lastpage) {
// if after deliting there are no rows on the current page
// which is the last page of the grid
newPage--; // go to the previous page
}
// reload grid to make the row from the next page visable.
grid.trigger("reloadGrid", [{page:newPage}]);
}
return true;
},
processing:true
}
}
},
You can use "jqGridAddEditAfterComplete" event, which will be triggered after deleting of rows by delGridRow, or you can use "jqGridAfterDelRow" alternatively, because delGridRow calls delRowData internally and jqGridAfterDelRow will be triggered by delRowData.
For deleting row use below code snippet:
$('#gridId').jqGrid('delRowData',rowid);
$("#yourGridTable").jqGrid(
"navGrid",
"#yourGridTablePager",
{
del: true
},
{},
{},
{
// This event is fired when delete button is pressed in pager
//
beforeSubmit:function(){
console.log("After delete button of pager is clicked");
}
}
);

JQGrid - header and column not align

Hope someone could point me to right direction..
I'm facing this problem for quite sometimes.!
http://imgur.com/j8S9ft5
I try some of the solutions which I found from stackoverflow
e.g.jqGrid column not aligned with column headers
& other sources but none solved my problem. This problem only arise after upgrading to Chrome 19 and above (I think!) and safari 6. I noticed theres no problem when viewed in my 2nd computer which is using safari 5 and when I reinstall Chrome ver 18.
I try updating some of the js and css file by downloading from trirand.net but come to no solution.
Currently I'm running Safari Version 6.0.1 (8536.26.14) and Chrome Version 26.0.1410.43.
thanks
UPDATE 2: after updating to 4.4.5 image http://imgur.com/NlY786x
& I forgot to mention this only happen when I integrate inside lightbox(facebox)
UPDATE 3:
#Oleg I just realise after after updating to 4.4.5 or just paste ur code (inside comment)
I'm not able to use my custom button anymore (working b4).. nothing happen.
I'm using a javascript & a php jqgrid, below is my code:
<div align="center" id="grido"> </div>
<script type="text/javascript">
//var lastSel;
$(document).ready(function(){
// $('#grido').load('form/housekeeping/dun_grid.php');
});
</script>
<script type="text/javascript">
<!-- dun_grid.js -->
jQuery(document).ready(function(){
var lastSel;
jQuery("#dun_grid").jqGrid({
url:'form/housekeeping/dun_griddata.php',
datatype: "json",
colNames:['DUN ID','DUN Code', 'DUN Name'],
colModel:[
{name:'int_dunid',index:'int_dunid', hidden:true, align:"center", width:50},
{name:'txt_dcode',index:'txt_dcode', editable:true, align:"center", width:150},
{name:'txt_dname',index:'txt_dname', editable:true, align:"center", width:150},
],
pager: '#pagerdun', //pagination enable
rowNum:15,
rowList:[10,20,30],
width:430,
height:'auto',
sortname: 'txt_dcode',
sortorder: 'asc',
hidegrid: false, //show/hide grid button on caption header
viewrecords: true, //display the number of total records
editurl:"form/housekeeping/dun.php?mode=edit",
loadtext: "Loading Data, Please Wait...",
rownumbers:true, // add row numbers on left side
caption: ' DUN List',
ondblClickRow: function(id){
if(id && id!==lastSel){
jQuery('#dun_grid').restoreRow(lastSel);
lastSel=id;
}
jQuery('#dun_grid').editRow(id, true, "", refreshing);
},
onSelectRow: function(id){
if(id && id!==lastSel){
jQuery('#dun_grid').restoreRow(lastSel);
lastSel=id;
}
},
}); /* end of jqgrid */
jQuery("#dun_grid").jqGrid('navGrid','#pagerdun',{edit:false, add:false, view:false, del:true, search:true},
{}, // edit
{}, // add
{url: 'form/housekeeping/dun.php?mode=delete'}, // delete
{multipleSearch : true},
{closeOnEscape:true}
); //end on navgrid
jQuery("#dun_grid").jqGrid('navButtonAdd','#pagerdun',{caption:"", buttonicon :'ui-icon-plus',
onClickButton:function(id){
jQuery('#dun_grid').restoreRow(lastSel);
var datarow = {txt_dname:""};
jQuery("#dun_grid").addRowData("0",datarow,"first");
jQuery('#dun_grid').editRow("0", true, "", tiesto);
lastSel=id;
},//end of onClickButton
title:"New Record",
position:"last"
}); //end of custom button
function refreshing(id){ /* refresh grid */
jQuery('#dun_grid').trigger("reloadGrid");
$.blockUI({ message:"Saving Data!!"});
setTimeout($.unblockUI, 700);
}
function tiesto(){
jQuery('#dun_grid').restoreRow(lastSel);
jQuery('#dun_grid').trigger("reloadGrid");
$.blockUI({ message:"New Data Saved!!"});
setTimeout($.unblockUI, 700);
}
}); /*end of document ready*/
</script>
<div align="center" class="gridpanel" >
<!--------------------------- ## grid for add/edit ## ------------------------------------------>
<table id="dun_grid" class="scroll" cellpadding="0" cellspacing="0"></table>
<!-- pager definition -->
<div id="pagerdun" class="scroll" style="text-align:center;"></div>
</div> <!----------------------- grid panel end -------------------------------------->
PHP
<?php
ini_set("display_errors","1");
require_once('../../Connections/jq-config.php');
// include the jqGrid Class
require_once "../../phpgrid/php/jqGrid.php";
// include the driver class
require_once "../../phpgrid/php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");
// Create the jqGrid instance
$grid = new jqGridRender($conn);
$grid->SelectCommand = 'SELECT int_bankid, txt_bank_code , txt_bank_name, txt_bank_address FROM tbl_bank';
// set the ouput format to json
$grid->dataType = 'json';
$grid->table ="tbl_bank";
$grid->setPrimaryKeyId("int_bankid");
$grid->setColModel();
$grid->setUrl('form/housekeeping/bank_grid.php');
$grid->setGridOptions(array("editurl"=>"form/housekeeping/bank.php?mode=edit"));
// Set grid option
$grid->setGridOptions(array(
"caption"=>" List of Banks",
"rownumbers"=>true,
"rowNum"=>10,
"rowList"=>array(10,20,50),
"sortname"=>"txt_bank_code",
"hoverrows"=>true,
"hidegrid"=>false,
"height"=>'auto',
"width"=>460,
"sortorder"=>'desc',
"loadtext" => "meloading data...",
"cmTemplate"=>array("searchoptions"=>array("sopt"=>array('eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc')))
));
// Change some property of the field(s)
$grid->setColProperty("int_bankid", array("label"=>"ID", "width"=>50, "align"=>"center", "hidden"=>true));
$grid->setColProperty("txt_bank_code", array("label"=>"Code", "width"=>60, "align"=>"center", "editrules"=>array("required"=>true)));
$grid->setColProperty("txt_bank_name", array("label"=>"Name", "width"=>130, "align"=>"center", "editrules"=>array("required"=>true)));
$grid->setColProperty("txt_bank_address", array("label"=>"Address", "width"=>200, "align"=>"center"));
// enable navbutton
$grid->navigator = true;
$grid->setNavOptions('navigator', array("pdf"=>false,"excel"=>false,"add"=>false,"edit"=>false,"del"=>true,"view"=>false ));
$grid->setNavOptions('del',array("url"=>"form/housekeeping/bank.php?mode=delete"));
// jscript for adding new row
$reloading = <<<RELOAD
function(id)
{
jQuery("#grid").trigger('reloadGrid');
}
RELOAD;
$mycode = <<<NEWBUTTON
function(id)
{
jQuery("#grid").jqGrid('restoreRow',lastSel);
jQuery("#grid").jqGrid('addRowData',"0",{txt_bank_code:''},"first");
jQuery("#grid").jqGrid('editRow', "0", true,'',$reloading);
lastSel=id;
}
NEWBUTTON;
//jscript for inline editing
$editrow = <<<DOUBLECLICK
function(rowid)
{
if (rowid && rowid !== lastSel) {
jQuery("#grid").jqGrid('restoreRow', lastSel);
lastSel = rowid;
}
jQuery("#grid").jqGrid('editRow', rowid, true,'',$reloading);
}
DOUBLECLICK;
//custom button setting for adding new row
$buttonoptions = array("#pager", array("caption"=>"", 'buttonicon' =>'ui-icon-circle-plus', "onClickButton"=> "js:".$mycode));
// inserting custom button
$grid->setGridEvent('ondblClickRow', $editrow);
$grid->callGridMethod("#grid", "navButtonAdd", $buttonoptions);
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
I had this same problem and was able to fix it by adjusting the CSS. I had set padding on the th which caused the issue.
It's possible that your th is inheriting padding which is messing up the alignment.
If the padding on the th is different than the grid cells (especially padding-left and right) it will break the alignment.
Try setting the property shrinkToFit as true;
shrinkToFit : true,
As given in the wiki
This option, if set, defines how the the width of the columns of the grid should be re-calculated, taking into consideration the width of the grid. If this value is true, and the width of the columns is also set, then every column is scaled in proportion to its width. For example, if we define two columns with widths 80 and 120 pixels, but want the grid to have a width of 300 pixels, then the columns will stretch to fit the entire grid, and the extra width assigned to them will depend on the width of the columns themselves and the extra width available.
Add this code into the gridComplete event of your grid. Don't forget to replace the gridName with your grid id:
var objHeader = $("table[aria-labelledby=gbox_" + gridName+ "] tr[role=rowheader] th");
for (var i = 0; i < objHeader.length; i++) {
var col = $("table[id=" + gridName+ "] td[aria-describedby=" + objHeader[i].id + "]");
var width= col.outerWidth();
$(objHeader[i]).css("width", width);
}
Works with v.4.6.0.
My Case
jqgrid version 4.6.0
Group Headers in the grid
shrinkTofit did not work
I called the following function in gridComplete event
function alignColumnsWithHeadersGENEL(gridName) {
var objHeaders = $("table[aria-labelledby=gbox_" + gridName + "] tr[class=jqg-first-row-header] th");
var objColumns = $("table[id=" + gridName + "] tr[class=jqgfirstrow] td");
for (var i = 0; i < objHeaders.length; i++) {
objHeaders[i].style.width = objColumns[i].style.width;
}
}
The structure of the HTML produced for my grid was something like the following(deleting the unnecessary fillings)
Somehow there were disrepancies between widths of the headers and columns

jqgrid in mvc with multiple delete

i want to add multiple delete functionality in my Jqgrid with MVC here there is code for my current grid in Action there is two thing View and delete but i want a check box and out side the grid one button when click on it the checked item should be delete and also before delete action fire message for confirmation please help.
$(document).ready(function ()
{
#if (ViewBag.Filters != string.Empty)
{
#Html.Raw(ViewBag.Filters);
}
$("#jq-grid").jqGrid({
url: '/Home/GetList',//Service URL to fetch data
datatype: 'json',//Data Type which service will return
mtype: 'GET',
postData://Data that will be posted with every request
{
filters: function () {
return $.toJSON([
//Here add the parameters which you like to pass to server
{ Key: "EmployeeName", Value: $("#txtEmployeeName").val() },
{ Key: "Id", Value: $("#txtId").val() }
]);
}
},
colNames: ['Employee Id', 'EmployeeName','empPhoto', 'Action'],//Column Names
colModel: [//Column details
{ name: "Employee Id", index: "Employee Id", width: "220px" },
{ name: "Employee Name", index: "EmployeeName", width: "220px" },
{ name: "empPhoto", index: "empPhoto", width: "50px" ,formatter:imageFormat },
//Do not allow sorting on Action Column
{ name: "Action", index: "Action", sortable: false, width: "220px" }
],
autowidth: true,//Do not use auto width
sortname: '#ViewBag.EmployeeGridRequest.sidx',//This will persist sorting column
sortorder: '#ViewBag.EmployeeGridRequest.sord', // This will persist sorting order
imgpath: '',//if some images are used then show grid's path
caption: 'Employee Grid List',//Grid's Caption, you can set it to blank if you do not want this
scrollOffset: 0,
rowNum: #ViewBag.EmployeeGridRequest.rows, //Total Pages
page: #ViewBag.EmployeeGridRequest.page, // Current Page
rowList: [#ViewBag.EmployeeGridRequest.rowList], // Page Selection Options
viewrecords: true,
// height: "100%",
altRows: true,//Use alternate row colors
altclass: 'jqgaltrow',//Alternate row class
hoverrows: true, //Do not hover rows on mouse over
pager: $('#jq-grid-pager'),//Div in which pager will be displayed
toppager: true,
pgbuttons: true,//Show next/previous buttons
loadtext:'Loading Data please wait ...',
//loadui :'block',//enable by default, block will disable inputs, remove this line if you do not want to block UI
loadComplete: function (response) //Incase you want to perform some action once data is loaded
{
}
});
});
This is one approach that I took after finding no built in solution that jqgrid api provides. Hope this helps. I took this approach because I wanted to allow deletion of those records that passed business rules and to alert user of those records where problem was found.
#jqGrid delete button
//Delete selected devices from jqgrid standard checkbox
jQuery("#jqDevice").jqGrid('navButtonAdd', '#jqDevicePager', {
caption: "",
title: "Delete selected records",
buttonicon: "ui-icon-trash",
position: "first",
onClickButton: function(){
//alert("edit button clicked");
var selIds = $("#jqDevice").getGridParam("selarrrow");
var len = selIds.length;
$("#dialogDeleteConfirm").dialog({
buttons : {
"Confirm" : function() {
//loop through each rows selected and delete
if(selIds.length > 0){
for(var i = len - 1; i >= 0; i--) { //traverse the selarrow array in reverse order.
//alert("Deleting Device... " + selIds[i]); //Test
$.ajax({
type: 'POST',
data: "deviceID=" + selIds[i],
url: '/Device/DeleteDeviceByID',
async: false,
success: function(data, textStatus){
//successfully deleted row
$("#jqDevice").delRowData(selIds[i]);
alert("Successfully deleted records...");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(JSON.parse(jqXHR.responseText));
}
});
}
}else{
alert("No rows selected.");
}
//Close Dialog after user confirms delete action
$(this).dialog("close");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
}
});
# Controller Action
public ActionResult DeleteDeviceByID(int deviceID)
{
try
{
//update LastModBy before deleting
Device device = _deviceRepository.GetDevice(deviceID);
device.LastModBy = User.Identity.Name;
_deviceRepository.SaveChanges();
_deviceRepository.DeleteDevice(deviceID);
}
catch (Exception ex)
{
//throw new Exception (ex.Message.Replace(Environment.NewLine, string.Empty));
//return Json(new { success = false, message = ex.Message.Replace(Environment.NewLine, string.Empty) });
//Good way to raise error in JSON format
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("There was a problem deleting ID - " + deviceID + " : " + ex.Message.Replace(Environment.NewLine, string.Empty) +
"\r\n\r\n Please try again. If the problem continues, please contact ... for further assistance.");
}
return Json(new { success = true });
}

jqgrid: Change editable cell to not editable according to the cell value in form editing

My problem is that i want to change the cell being editable or not in the edit form according to the content of the cell of the row that is selected to be edited.
I used Oleg's example to this link: JQGrid: Dynamically set a cell to uneditable based on content to figure out how to change the cell from editable to not editable but i cannot get the cell value in order to compare it and decide if i want to change the edit option of the cell.
UPDATED CODE:
var Setcelluneditable=function(form) {
return function (form) {
var id = jQuery(list).getGridParam('selrow');
var ret = jQuery(list).jqGrid('getRowData',id);
alert("Arrived="+ret.Arrived);
if (ret.Arrived=='Yes')
{alert("hello"+id);
jQuery(list).setCell(id,'Arrived','',{color:'red'}, editable:'0'});}
}
};
jQuery(list).jqGrid('navGrid',pager,{edit:true,add:true,del:true,search:false,view:true, reload:true},
{
width:colwidth,
height:"auto",
reloadAfterSubmit:true,
closeAfterEdit: true,
recreateForm: true,
ajaxEditOptions: {cache: false},
beforeInitData : Setcelluneditable("#editmod")
},
{
width:colwidth,
height:"auto",
reloadAfterSubmit:true,
closeAfterAdd: true,
recreateForm: true,
drag: false
},
{},
{},
{},
{});
This does not seem to work because i change the Grid that has already been constructed.
I think i found out the way to do that but it does not seem to me the best one can have:
onSelectRow: function(id){
var ret = jQuery(list).jqGrid('getRowData',id);
if (ret.Arrived=='Yes')
{
jQuery(list).setColProp('Arrived',{editable:false});}
else { jQuery(list).setColProp('Arrived',{editable:true});}}
I change the ColProp every time one Selects a Row.
selRowId = $(list).jqGrid ('getGridParam', 'selrow');
var cm = $(list).jqGrid('getGridParam', 'colModel');
for(x=0; x<cm.length; x++){
if(cm[x].name == 'ID'){
$('#' + selRowId + '_' + cm[x].name).attr('disabled', true);
}
}
code in onSelectRow event

jqgrid Subgrid as a Grid: Edit, Add, Search Icons not appearing in Subgrid

This is the code for my Grid. But for some reason the edit, add, and search icons are not displaying in subgrid:
$(document).ready(function(){
var gridwidth = $('.tableContainer').width();
gridwidth = gridwidth-40;
var myGrid = jQuery("#list");
editSettings = {
recreateForm:true,
reloadAfterSubmit:false,
closeOnEscape:true,
closeAfterEdit:true,
width:"1250"
},
addSettings = {
recreateForm:true,
reloadAfterSubmit:false,
closeOnEscape:true,
closeAfterAdd:true
};
myGrid.jqGrid(
{
url:'projects.cfc?method=getProjects&returnformat=json&_cf_nodebug=true', //CFC that will return the projects
datatype: 'json', //We specify that the datatype we will be using will be JSON
complete: function(jsondata, stat) {
if (stat == "success") {
myGrid = jQuery("#list")[0];
myGrid.addJSONData(JSON.parse(jsondata.responseText).d);
} else {
alert('Error processing JSON');
}
},
colNames:[ .....],
colModel :[{ ...}], //it the operators available during search
pager: $('#pager'), //The div we have specified, tells jqGrid where to put the pager
rowNum: 150, //Number of records we want to show per page
rowList:[20,30,40,50,75,150], //Row List, to allow Initiative to select how many rows they want to see per page
sortorder: "asc", //Default sort order
sortname: "PROJECTS.PROJECTID", //Default sort column
viewrecords: true, //Shows the nice message on the pager
imgpath: '/images', //Image path for prev/next etc images
caption: 'Initiatives', //Grid Name
recordtext: "Record {0} - {1} of {2}",//Pager information to show
rownumbers: false,//Do not show row numbers
sortable: true,
width:'auto',
height:'auto', //I like auto, so there is no blank space between. Using a fixed height can mean either a scrollbar or a blank space before the pager
mtype:'POST',
toolbar:[true,"bottom"], //Shows the toolbar at the top. We will use it to display Initiative feedback
subGrid: true,
subGridRowExpanded: function(subgrid_id, row_id) {
// we pass two parameters
// subgrid_id is a id of the div tag created within a table
// the row_id is the id of the row
// If we want to pass additional parameters to the url we can use
// the method getRowData(row_id) - which returns associative array in type name-value
// here we can easy construct the following
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_t";
pager_id = "p_" + subgrid_table_id;
jQuery("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' cellpadding='0' cellspacing='0' class='scroll'></table><div id=’" + pager_id + "’ class=’scroll’></div>");
jQuery("#"+subgrid_table_id).jqGrid({
url:"projects.cfc?method=getProjectMilestones&projectid="+row_id,
datatype: "json",
colNames:['SEQ','ID','MILESTONE','TREND','DUE DATE','STATUS','OWNERS','%','COMMENTS'], //Column Names
//The Column Model to define the data. Note you can make columns non sortable, specify width, alignment, etc.
colModel :[
{name:'SEQUENCENUM',index:'SEQUENCENUM',hidden:true},
{name:'PROJECTID',index:'PROJECTID', editable:false},
{name:'MILESTONE',index:'MILESTONE', width:150, sorttype:"text",align:"center",
editable:true,edittype:"text",
editrules:{required:true}},
{name:'TREND',index:'TREND', width:100, align:"center",sorttype:"text",
editable:true,edittype:"select",editoptions:{value:"Green:Green;Yellow:Yellow;Red:Red"},
editrules:{required:true}},
{name:'DUE_DATE',index:'DUE_DATE', width:150, editable:true,editoptions:{size:12,dataInit: function(el) {
$(el).datepicker({ dateFormat: 'mm-dd-yy'} );
},
defaultValue: function() {
var currentTime = new Date();
var month = parseInt(currentTime.getMonth() + 1);
month = month <= 9 ? "0" + month : month;
var day = currentTime.getDate();
day = day <= 9 ? "0" + day : day;
var year = currentTime.getFullYear();
return month + "-" + day + "-" + year ;
}
},align:"center",
editrules:{required:true}},
{name:'MILESTONE_STATUS',index:'MILESTONE_STATUS',
editable:true,edittype:"select",editoptions:{value:"In Progress:In Progress;Complete:Complete"},
editrules:{required:true}},
{name:'ASSIGNMENT',index:'ASSIGNMENT', width:125,align:"center",sorttype:"text",
editable:true,edittype:"text",
editrules:{required:true}},
{name:'PERCENT_COMP',index:'PERCENT_COMP', width:50, sorttype:"int",align:"center",
editable:true,edittype:"text",editrules:{number:true}},
{name:'COMMENTS',index:'COMMENTS', width:200,
editable:true,edittype:"textarea",editoptions:{rows:3, cols:30},
editrules:{required:true}}
],//searchoptions parameter is used to limit the operators available during search,
rowNum: 20, //Number of records we want to show per page
rowList:[20,30,40,50], //Row List, to allow Initiative to select how many rows they want to see per page
sortorder: "asc", //Default sort order
sortname: "SEQUENCENUM", //Default sort column
viewrecords: true, //Shows the nice message on the pager
imgpath: 'images/', //Image path for prev/next etc images
caption: 'Milestones', //Grid Name
recordtext: "Record {0} - {1} of {2}",//Pager information to show
rownumbers: false,//Do not show row numbers
sortable: true,
width:'auto',
height:'auto', //I like auto, so there is no blank space between. Using a fixed height can mean either a scrollbar or a blank space before the pager
mtype:'POST',
toolbar:[true,"bottom"], //Shows the toolbar at the top. We will use it to display Initiative feedback
shrinkToFit: true,
//The JSON reader. This defines what the JSON data returned from the CFC should look like
jsonReader: {
root: "ROWS", //our data
page: "PAGE", //current page
total: "TOTAL", //total pages
records:"RECORDS", //total records
userdata:"USERDATA",
cell: "", //Not Used
id: "0", //Will default to first column
subGrid: {
root : "ROWS",
repeatitems: true,
cell: "" //Not Used
}
},
editurl:'projects.cfc?method=addeditMilestone&projectid='+row_id, //The Add/Edit function call
pager:('#' + pager_id)
}).navGrid('#' + pager_id, {
search:false,//title set for hover over display
edit:true,edittitle:"Edit Milestone",width:200,
add:true,addtitle:"Add Milestone",width:200,
del:true,deltitle:"Delete Milestone"
},
// Edit Options. save key parameter will keybind the Enter key to submit.
{editCaption:"Edit Milestone",edittext:"Edit",closeOnEscape:true,closeAfterEdit:true,savekey: [true,13],errorTextFormat:commonError,width:"500"
,reloadAfterSubmit:true,bottominfo:"Fields marked with (*) are required",top:"60",left:"5",right:"5"},
{addCaption:"Add Milestone",closeOnEscape:true,closeAfterAdd:true,savekey: [true,13],errorTextFormat:commonError,width:"500"
,reloadAfterSubmit:true,bottominfo:"Fields marked with (*) are required",top:"60",left:"5",right:"5"},
//Add Options
{url:"projects.cfc?method=delMilestone",caption:"Delete Milestone",closeOnEscape:true,errorTextFormat:commonError,top:"60",left:"70",
reloadAfterSubmit:true} //Delete Options
)
},
shrinkToFit: true,
//The JSON reader. This defines what the JSON data returned from the CFC should look like
jsonReader: {
root: "ROWS", //our data
page: "PAGE", //current page
total: "TOTAL", //total pages
records:"RECORDS", //total records
userdata:"USERDATA",
cell: "", //Not Used
id: "0" //Will default to first
},
loadComplete: function() {
$('#cb').prev().remove();
if($("#list").getGridParam("RECORDS")==0){
$('#noResults').dialog("open");
} else {
var page = $('#list').getGridParam("PAGE");
var records = $('#list').getGridParam("RECORDS");
var recordsPP = $('#list').getGridParam("rowNum");
var x = records/recordsPP;
var returnArray = [];
if(x < page) {
iterLimit = records%recordsPP;
} else {
iterLimit = recordsPP;
}
for(var i=1; i<=iterLimit; i++) {
$('#'+i).children('td:first').next().addClass('link').css("cursor","pointer").css("color","blue").css("text-decoration","underline");
var emitid = $('#'+i).children ('td:first').next().text();
//window.alert(emitid);
$('#'+i).children('td:first').next().click(function() {
emitid = $(this).text();
//window.alert(emitid + ":" + page + ":" + records + ":" + recordsPP + ":" + x);
var link = 'viewInitiative.cfm?projectid='+emitid
window.open(link,'_blank');
});
//returnArray = orderList.find(ord);
var truefalse = typeof returnArray;
if(truefalse != 'boolean') {
$('#list').setSelection(i);
}
}
}
},
loadError:function(xhr, st, err) {
alert('loaderror on quote request grid - ' + st)
},
editurl:"projects.cfc?method=addeditProject", //The Add/Edit function call
ondblClickRow: function(rowid, ri, ci) {
var p = myGrid[0].p;
if (p.selrow !== rowid) {
// prevent the row from be unselected on double-click
// the implementation is for "multiselect:false" which we use,
// but one can easy modify the code for "multiselect:true"
myGrid.jqGrid('setSelection', rowid);
}
myGrid.jqGrid('editGridRow', rowid, editSettings);
}
}).navGrid('#pager',
{
search:true,searchtitle:"Search",//title set for hover over display
edit:true,edittitle:"Edit Initiative",width:1000,
add:true,addtitle:"Add Initiative",width:1000,
del:true,deltitle:"Delete Initiative"
},
// Edit Options. save key parameter will keybind the Enter key to submit.
{editCaption:"Edit Initiative",edittext:"Edit",closeOnEscape:true,closeAfterEdit:true,savekey: [true,13],errorTextFormat:commonError,width:"1250"
,reloadAfterSubmit:true,bottominfo:"Fields marked with (*) are required",top:"60",left:"5",right:"5"},
{addCaption:"Add Initiative",closeOnEscape:true,closeAfterAdd:true,savekey: [true,13],errorTextFormat:commonError,width:"1250"
,reloadAfterSubmit:true,bottominfo:"Fields marked with (*) are required",top:"60",left:"5",right:"5"},
//Add Options
{url:"projects.cfc?method=delProject",caption:"Delete Initiative",closeOnEscape:true,errorTextFormat:commonError,top:"60",left:"70",
reloadAfterSubmit:true}, //Delete Options
//Search Options. multipleSearch parameter lets it know we are going to use the new advanced search feature
{errorTextFormat:commonError,Find:"Search",closeOnEscape:true,caption:"Search Initiatives",multipleSearch:true,closeAfterSearch:true}
).navButtonAdd('#pager',{
caption:"Export to Excel",
buttonicon:"images/sizzlejs_32x32.png",
onClickButton: function(){
exportExcel();
},
position:"last"
});
function exportExcel()
{
var mya=new Array();
mya=$("#list").getDataIDs(); // Get All IDs
var data=$("#list").getRowData(mya[0]); // Get First row to get the labels
var colNames=new Array();
var ii=0;
for (var i in data){colNames[ii++]=i;} // capture col names
var html="";
for (var k=0;k<colNames.length;k++)
{
if(colNames[k] == "PROJECTID") {
html=html+"EMIT_ID"+"\t";
} else if (colNames[k] == "PROJECT_TITLE") {
html=html+"INITIATIVE_TITLE"+"\t";
} else if (colNames[k] == "PROJECT_TYPE") {
html=html+"SUB-CATEGORY"+"\t";
} else if (colNames[k] == "PROJECT_TYPEID") {
html=html+"SUB_CAT_ID"+"\t";
} else if (colNames[k] == "SUB_TEAM") {
html=html+"SUB_TEAM_MEMBERS"+"\t";
} else if (colNames[k] == "OVERRIDE") {
html=html+"OVERRIDE%_COMP"+"\t";
} else if (colNames[k] == "EM_EXECUTION_TOP_TEN") {
html=html+"EM_EXECUTION_PAIN_POINT"+"\t";
} else {
html=html+colNames[k]+"\t"; // output each Column as tab delimited
}
}
html=html+"\n";
for(i=0;i<mya.length;i++)
{
data=$("#list").getRowData(mya[i]); // get each row
for(j=0;j<colNames.length;j++)
{
html=html+data[colNames[j]]+"\t"; // output each column as tab delimited
}
html=html+"\n"; // output each row with end of line
}
html=html+"\n"; // end of line at the end
document.forms[0].csvBuffer.value=html;
document.forms[0].method='POST';
document.forms[0].action='http://bfops01.edc.cingular.net/excel/csvExport.php'; // send it to server which will open this contents in excel file
document.forms[0].target='_blank';
document.forms[0].submit();
}
//Function will be called when add/edit encounters an error. The returned message is what will be shown to Initiative
function commonError(data){
return "Error Occured during Operation. Please try again";
}
});
You should verify your code in the http://www.jslint.com/. It has many syntax errors. For example, you forget to declare variables iterLimit and j, you should replace ';' after var myGrid = jQuery("#list") to ',' and many other small problems. I recommend you additionally to use integer values for width parameter in many places of the code like jqGrid use ifself.
You main problem seems to me exist because the <div> for the subgrid will be either not created or has no or wrong id element. The code
jQuery("#"+subgrid_id).html("<table id='"+subgrid_table_id+
"' cellpadding='0' cellspacing='0' class='scroll'></table><div id=’" +
pager_id + "’ class=’scroll’></div>");
contain special character ’ instead of '. It should be replaced to
jQuery("#"+subgrid_id).html("<table id='"+subgrid_table_id+
"'></table><div id='" + pager_id + "'></div>");
You use very very old syntax for HTML elements and use retro parameters like imgpath which are deprecated since version 3.5 of jqGrid.

Resources