Formatters give incorrect result after sort or search - jqgrid

I have following code using free-jqgrid. It loads correctly for the first time (Status is “Active” and Partner? is “Yes”). But when I do a sort or search, the values become incorrect(Status is “Retired” and Partner? is “No”).
Why the formatters are giving incorrect values? How to fix this?
SCRIPT
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/start/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.6/js/jquery.jqgrid.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.6/css/ui.jqgrid.min.css" rel="stylesheet" />
<script type="text/javascript">
function getCurrentPractice ()
{
return "Test";
}
function getGridCaption() {
return "<div style='font-size:15px; font-weight:bold; display:inline; padding-left:10px;'><span class='glyphicon glyphicon-check' style='margin-right:3px;font-size:14px;'></span>" + getCurrentPractice() + " " + "</div>" +
"<div style='float:right; padding-right:20px; padding-bottom:10px; display:inline;>" +
"<div style='float:right;width:550px; padding-bottom:20px;'>" +
"<input type='text' class='form-control' id='filter' placeholder='Search' style='width:250px; height:30px; float:right; ' />" +
" </div>" +
"</div>";
}
$(function () {
var currentPractice = "P";
var grid = $("#list2");
grid.jqGrid({
url: '/Home/GetProviders',
datatype: "json",
postData:
{
practiceName: function () { return currentPractice }
},
colNames: [
'Practice',
'ProviderID',
'Partner?',
'Status'
],
colModel: [
{ name: 'Practice', hidden: false },
{ name: 'ProviderID', hidden: false },
{
name: 'PartnerStatusText',
width: 70,
formatter: function (cellvalue, options, rowObject) {
var isPartner = rowObject.IsPartner;
return isPartner == true ? 'Yes' : 'No';
}
},
{
name: 'ActiveStatusText',
width: 70,
formatter: function (cellvalue, options, rowObject) {
var isActive = rowObject.IsActive;
return isActive == true ? 'Active' : 'Retired';
}
}
],
ignoreCase: true,
loadonce: true,
rowNum: 25,
rowList: [15, 25, 35, 50],
pager: '#pager2',
viewrecords: true,
sortable: true,
caption: getGridCaption(),
beforeSelectRow: function (rowid, e) {
//Avoid selection of row
return false;
},
loadComplete: function () {
}
});
grid.jqGrid('navGrid', '#pager2', { edit: false, add: false, del: false });
//Filter Toolbar
$("#advancedSearch").click(function () {
grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
});
//Top Search
$("#filter").on('keyup', function () {
var searchFiler = $("#filter").val(), f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, { filters: "" });
}
f = { groupOp: "OR", rules: [] };
f.rules.push({ field: "Practice", op: "cn", data: searchFiler });
grid[0].p.search = true;
$.extend(grid[0].p.postData, { filters: JSON.stringify(f) });
grid.trigger("reloadGrid", [{ page: 1, current: true }]);
});
});
</script>
</head>
HTML
<div style="float:left; border:1px solid red;">
<div id="divGrid" style="width: 680px; min-height: 50px; float: left; border: 1px solid silver;">
<table id="list2"></table>
<div id="pager2"></div>
</div>
</div>
Server Code
[AllowAnonymous]
public JsonResult GetProviders(string practiceName)
{
//System.Threading.Thread.Sleep(3000);
List<Provider> providers = new List<Provider>();
Provider p = new Provider();
p.Practice = "Test1";
p.ProviderID = 1;
p.IsActive = true;
p.IsPartner = true;
providers.Add(p);
Provider p2 = new Provider();
p2.Practice = "Test2";
p2.ProviderID = 2;
p2.IsActive = true;
p2.IsPartner = true;
providers.Add(p2);
return Json(providers, JsonRequestBehavior.AllowGet);
}
UPDATE
Thanks to Oleg, working demo can be found here - Fiddle . It uses "/echo/json/" service of JSFiddle to get data from server.
It uses sorttype and additionalProperties. This can be rewritten without additionalProperties - I need to do it when I get a chance to revisit this.

The problem seems be very easy. The data returned from the server contains properties Practice, ProviderID, IsActive and IsPartner. The properties are available in rowObject during initial loading. You use additionally loadonce: true option. Thus free jqGrid will try to save some data locally, but which one? jqGrid saves by default the properties which corresponds the names of columns: Practice, ProviderID, PartnerStatusText and ActiveStatusText, but jqGrid have no information that other properties IsActive and IsPartner need be saved too.
You can solve the problem in two alternative ways:
you rename the column names PartnerStatusText and ActiveStatusText to IsActive and IsPartner.
you add the option additionalProperties: ["IsActive", "IsPartner"] to inform jqGrid to read and save locally additional properties.
Moreover, I'd recommend you to use options.rowData instead of rowObject inside of custom formatter. You can skip the 3-d parameter and to use formatter: function (cellvalue, options) {...}.
The final remark: the current code of the custom formatter is very easy. You need to replace some input values (true and false) to another text. One can use formatter: "select" for the case:
colModel: [
{ name: "Practice" },
{ name: "ProviderID" },
{
name: "IsPartner",
width: 70,
formatter: "select",
formatoptions: { value: "false:No;true:Yes" }
},
{
name: "IsActive",
width: 70,
formatter: "select",
formatoptions: { value: "false:Retired;true:Active" }
}
],
See https://jsfiddle.net/c9fge9yk/1/

Related

why react's babel throws duplicate object error, jqgrid on IE?

i have loaded the following jqGrid grid in regards to car annual check up for maintenance data.
On chrome this looks like this:
This was generated as a react object, the code as follows:
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/start/jquery-ui.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.6/css/ui.jqgrid.min.css" />
</head>
<body>
<div id="divContainer"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
$.jgrid = $.jgrid || {};
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;
</script>
<script src="https://rawgit.com/free-jqgrid/jqGrid/master/js/jquery.jqgrid.src.js"></script>
<script type="text/babel" src="sample.jsx">
</script>
</body>
</html>
JSX code:
var SampleGrid = React.createClass({
componentDidMount:function(){
this.gridLoad();
},
gridLoad:function(){
var mydata = [
{ id: "1", test: "Engine checkup", teststart: "12/12/2016", testend: "12/30/2016", passed: true},
{ id: "2", test: "Electrical Checkup", teststart: "1/2/2017", testend: "1/3/2017", passed: false},
{ id: "3", test: "Chasis checkup", teststart: "1/4/2017", testend: "1/5/2017", passed: false},
{ id: "4", test: "Aerodynamics checkup", teststart: "1/6/2017", testend: "1/9/2017", passed: true},
{ id: "5", test: "Balance and stability checkup", teststart: "1/10/2017", testend: "1/12/2017", passed: true},
{ id: "6", test: "Report", teststart: "", testend: "", closed: false }
];
jQuery("#grid100").jqGrid({
colNames: ['test','passed','test started','test ended'],
colModel: [
{name: 'test', index: 'test', width: 220 },
{name: 'passed', index: 'passed', width: 60, align: 'center', formatter: 'checkbox',
edittype: 'checkbox', editoptions: {value: 'Yes:No', defaultValue: 'Yes'}, formatoptions: { disabled: false},
cellattr: function(rowId, tv, rawObject, cm, rdata) {
if (Number(rowId) == 6) { return ' colspan="3"' }},
formatter:function(cellvalue, options, rowObject)
{
if(rowObject.id==6)
{
return '<input type="text" id="txtnotes" ref="refnotes" />';
}
else
{
if(rowObject.passed===true)
{
return '<input type="checkbox" id="cbPassed-'+ rowObject.id +'" checked/>';
}
else
{
return '<input type="checkbox" id="cbPassed-'+rowObject.id+ '" />';
}
}
}
},
{name: 'teststart', index: 'teststart', width: 75, formatter: 'string', sorttype: 'string', align: 'center',
cellattr: function(rowId, tv, rawObject, cm, rdata) {
if (Number(rowId) == 6) { return ' style="display:none;"' }}},//return ' colspan="5"'
{name: 'testend', index: 'testend', width: 75, formatter: 'string', sorttype: 'string', align: 'center',
cellattr: function(rowId, tv, rawObject, cm, rdata) {
if (Number(rowId) == 6) { return ' style="display:none;"' }}}
],
rowNum: 10,
rowList: [5, 10, 20],
threeStateSort:true,
gridview: true,
rownumbers: false,
autoencode: true,
ignoreCase: true,
sortname: "id",
viewrecords: true,
sortorder: "desc",
shrinkToFit: false,
});
for(var i=0;i<=mydata.length;i++)
jQuery("#grid100").jqGrid('addRowData',i+1,mydata[i]);
jQuery("#grid100").jqGrid('setGroupHeaders', {
useColSpanStyle: true,
groupHeaders:[
{startColumnName: 'passed', numberOfColumns: 3, titleText: 'Test Duration'}
]
});
},
render:function(){
return(<div id="gridContainer" ref="refContainer">
<form>
<table id="grid100"></table>
</form>
</div>
)
}
})
ReactDOM.render(<SampleGrid />, document.getElementById('divContainer'));
But this behaves funny. when i ran the code in chrome it works perfectly fine but when i ran this on IE (my version is 10) it gives the following error on console
SCRIPT1046: Multiple definitions of a property not allowed in strict mode
At the moment i cannot figure out why the same code produces results in one browser and not in another. But i know this error raised since i have added the formater to the column passed
formatter:function(cellvalue, options, rowObject)
{
if(rowObject.id==6)
{
return '<input type="text" id="txtnotes" ref="refnotes" />';
}
else
{
if(rowObject.passed===true)
{
return '<input type="checkbox" id="cbPassed-'+ rowObject.id +'" checked/>';
}
else
{
return '<input type="checkbox" id="cbPassed-'+rowObject.id+ '" />';
}
}
}
How do i fix this issue?
The reason of the problem: the usage of multiple formatter property for the column passed (see formatter: 'checkbox', ..., formatter:function(cellvalue, options, rowObject) {...}). You should remove or comment the formatter: 'checkbox' from your code.
I'd recommend you additionally:
never fill the grid with data using addRowData in the loop. You should remove the lines for(var i=0;i<=mydata.length;i++) jQuery("#grid100").jqGrid('addRowData',i+1, mydata[i]); from your code. Additionally you should add data: mydata parameter and to remove unneeded sortorder: "desc" option.
to remove all index properties from colModel
remove unneeded options gridview: true, rownumbers: false, ignoreCase: true. All the values are already defaults in free jqGrid.

How to disable the cell if the date is empty or null or undefined?

I'm new to jqgrid and jquery, can someone please help me in disabling the cell when the date is null or empty or undefined?
Actually the json for some (rows,col) date data is there and for some it is not there.
I want to disable the cell in the row for which Date data is not available.
grid cell editing POC
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="/jqGrid/jquery-ui-1.11.4.custom/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="/jqGrid/Guriddo_jqGrid_JS_5.0.1/css/ui.jqgrid.css">
<script type="text/ecmascript" src="/jqGrid/Guriddo_jqGrid_JS_5.0.1/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/jqGrid/jquery-ui-1.11.4.custom/jquery-ui.min.js"></script>
<script type="text/javascript" src="/jqGrid/Guriddo_jqGrid_JS_5.0.1/js/i18n/grid.locale-en.js"></script>
<script type="text/javascript">
$.jgrid.useJSON = true;
</script>
<script type="text/javascript" src="/jqGrid/Guriddo_jqGrid_JS_5.0.1/src/jquery.jqGrid.js"></script>
<script type="text/javascript">
$(function () {
"use strict";
var grid = $("#tree");
var initDateWithButton = function (elem) {
var ids = grid.jqGrid('getDataIDs');
for (var i=0;i<ids.length;i++) {
var id=ids[i];
if (grid.jqGrid('getCell',id,'assignedDate') == null) {
grid.jqGrid('setCell',id,'assignedDate','','not-editable-cell');
}
if (grid.jqGrid('getCell',id,'assignedDate') == "") {
grid.jqGrid('setCell',id,'assignedDate','','not-editable-cell');
}
if (grid.jqGrid('getCell',id,'assignedDate') == undefined) {
grid.jqGrid('setCell',id,'assignedDate','','not-editable-cell');
}
}
if (/^\d+%$/.test(elem.style.width)) {
// remove % from the searching toolbar
elem.style.width = '';
}
// to be able to use 'showOn' option of datepicker in advance searching dialog
// or in the editing we have to use setTimeout
setTimeout(function () {
$(elem).datepicker({
dateFormat: 'dd-M-yy',
showOn: 'button',
changeYear: true,
changeMonth: true,
showWeek: false,
showButtonPanel: true,
buttonImage: 'http://rcban0015:10039/GridPOC/pages/calenderIcon.gif',
onClose: function (dateText, inst) {
inst.input.focus();
}
});
$(elem).next('button.ui-datepicker-trigger').button({
text: false,
position: "relative",
top: "4px"
});
}, 100);
},
dateTemplate = {align: 'center', sorttype: 'date', editable: true,
formatter: 'date', formatoptions: { newformat: 'd-M-Y' }, datefmt: 'd-M-Y',
editoptions: { dataInit: initDateWithButton, size: 11 },
searchoptions: {
sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
dataInit: initDateWithButton,
size: 11, // for the advanced searching dialog
attr: {size: 11} // for the searching toolbar
}},
lastSel;
jQuery('#tree').jqGrid({
url: '<%= webAppAccess.getBackchannelActionURL("actionListjqGridPagination",false) %>',
"colModel":[
{
"name":"course_id",
"index":"course_id",
"sorttype":"int",
"key":true,
"hidden":true,
"width":50
},{
"name":"courseName",
"index":"courseName",
"sorttype":"string",
"label":"courseName",
"width":200
},{
"name":"facility",
"index":"facility",
"label":"facility",
"width":200,
"align":"left"
},{
"name":"assignedDate",
"index":"assignedDate",
"label":"assignedDate",
"width":110,
"template": dateTemplate
},{
"name":"dueDate",
"index":"dueDate",
"label":"dueDate",
"width":110,
"template": dateTemplate
},
{
"name":"AssignmentStatus",
"index":"AssignmentStatus",
"label":"AssignmentStatus",
"width":50
},{
"name":"Action",
"index":"Action",
"label":"Action",
"width":50
},
{
"name":"lft",
"hidden":true
},{
"name":"rgt",
"hidden":true
},{
"name":"level",
"hidden":true
},{
"name":"uiicon",
"hidden":true
}
],
"jsonReader": { "repeatitems": false, "root": "employees.rows" },
"toolbar": [true, "top"],
"width":"1200",
"hoverrows":false,
"viewrecords":false,
"gridview":true,
"height":"auto",
"sortname":"lft",
"loadonce":true,
"rowNum": 2,
"rowList":[2,10,15],
"scrollrows":true,
// enable tree grid
"treeGrid":true,
// which column is expandable
"ExpandColumn":"courseName",
// datatype
"treedatatype":"json",
// the model used
"treeGridModel":"nested",
// configuration of the data comming from server
"treeReader":{
"left_field":"lft",
"right_field":"rgt",
"level_field":"level",
"leaf_field":"isLeaf",
"expanded_field":"expanded",
"loaded":"loaded",
// set the ui icon field froom data
"icon_field":"uiicon"
},
"sortorder":"asc",
"datatype":"json",
"pager":"#pager",
"cellEdit": true, // TRUE = turns on celledit for the grid.
"cellsubmit" : 'clientArray',
"editurl": 'clientArray'
});
$('#t_' +"tree")
.append($("<div><label for=\"globalSearchText\">Global search in grid for: </label><input id=\"globalSearchText\" type=\"text\"></input> <button id=\"globalSearch\" type=\"button\">Search</button></div>"));
$("#globalSearchText").keypress(function (e) {
var key = e.charCode || e.keyCode || 0;
if (key === $.ui.keyCode.ENTER) { // 13
$("#globalSearch").click();
}
});
$("#globalSearch").button({
icons: { primary: "ui-icon-search" },
text: false
}).click(function () {
var postData = jQuery('#tree').jqGrid("getGridParam", "postData"),
colModel = jQuery('#tree').jqGrid("getGridParam", "colModel"),
rules = [],
searchText = $("#globalSearchText").val(),
l = colModel.length,
i,
cm;
for (i = 0; i < l; i++) {
cm = colModel[i];
if (cm.search !== false && (cm.stype === undefined || cm.stype === "text")) {
rules.push({
field: cm.name,
op: "cn",
data: searchText
});
}
}
postData.filters = JSON.stringify({
groupOp: "OR",
rules: rules
});
jQuery('#tree').jqGrid("setGridParam", { search: true });
jQuery('#tree').trigger("reloadGrid", [{page: 1, current: true}]);
return false;
});
});
</script>
</head>
<body>
<table id="tree"><tr><td></td></tr></table>
<div id="pager"></div>
</body>
</html>
There are exist alternative fork of jqGrid: free jqGrid, which I develop since more as one year. It has the functionality, where one can define editable property of colModel as function, which can return true or false based on the cell or the row content. See the wiki article for more details.
Check if this How to disable editing for soe cells in row editing of JQGrid
helps, it seen it is a similar thing, You just need to add into your logic.

Getting only modified or new Kendo UI Grid rows to send to the server

Although I have tried several times, I could not solve trying many method.
Shortly this is the thing what I want to do : only get modified or new rows as an object or JSON string.
You should use set for changing the content of a record. Then, getting the records modified is just iterating through datasource.data() array and checking which items have dirty set to true.
var data = grid.dataSource.data();
var dirty = $.grep(data, function(item) {
return item.dirty
});
// Dirty array contains those elements modified
console.log("dirty", dirty);
The following snippet shows both that changing the data programmatically or via Grid built-in incell edition is compatible with this approach.
$(document).ready(function() {
var crudServiceBaseUrl = "http://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
Discontinued: { type: "boolean" }
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
height: 300,
columns: [
"ProductName",
{ field: "Discontinued", width: 120 }
],
editable: "incell",
selectable: true
}).data("kendoGrid");
$("#change").on("click", function() {
var sel = grid.select();
if (sel.length) {
var item = grid.dataItem(sel);
item.set("Discontinued", true);
}
});
$("#show").on("click", function() {
var data = grid.dataSource.data();
var dirty = $.grep(data, function(item) {
return item.dirty
});
$("#logger").html(JSON.stringify(dirty, null, 2));
});
});
#logger {
min-height: 60px;
border: 1px solid black;
overflow-x: scroll
}
#grid {
width: 500px;
}
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.default.min.css" />
<script src="http://cdn.kendostatic.com/2014.3.1119/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1119/js/kendo.all.min.js"></script>
<div id="example">
<div>
This button changes the Discontinued field to "true" for the selected row:
<button id="change" class="k-button">Change selected</button>
</div>
<div>
Click for displaying modified rows:
<button id="show" class="k-button">Show dirty</button>
<pre id="logger"></pre>
</div>
<div id="grid"></div>
</div>

JqGrid frozen column

I've been trying to add frozen column in my jqgrid but i found out there is bug with the last row of my data.
.
.
.
{name:'Code',index:'txt_site_code', hidden:false, align:'center', width:70, frozen:true }
.
.
}); /* end of jqgrid */
jQuery("#production").jqGrid('setFrozenColumns');
Why does the last row does not froze as it should. It will move with the horizontal scroller.
I saw the same 'bug' in trirand.com and trirand.net DEMO on FROZEN COLUMN topic. Any idea on how to solve this..?
thanks..
This happens when the height of the table is not equal to the height of the Div in which it is nested.
You can use jQuery to reassign the height of the table which is frozen.
Note: Use this on GridComplete Function.
$(".frozen-bdiv").height(j$(".frozen-bdiv").find("table").height());
The column height issue has not been resolved in jqGrid4.8.2. Using Oleg's solution from 'How to make Jqgrid frozen column word-wrap' works. See my code sample.
May you can add an onchange method.
This worked for me:
Add new height adjustment method:
function rowsHeightAdjust(){
editableRows = $("#jqGrid").find("tr");
frozenRows = $("#jqGrid_frozen").find("tr");
for (indexRow=0; indexRow<frozenRows.length;indexRow++){
if(indexRow > 0 && typeof(editableRows[indexRow]) != 'undefined') {
$(frozenRows[indexRow]).height($(editableRows[indexRow]).height());
}
}
}
Call the method on some event, eg:
//every time we change something on editable fields
$(".editable").change(function(){ rowsHeightAdjust() });
Jqgrid creates a new frozen table overlapping the editable one.
This method takes the frozen rows and makes each height match to editable row.
Hope you'll find it helpful.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- A link to a jQuery UI ThemeRoller theme, more than 22 built-in and many more custom -->
<link rel="stylesheet" type="text/css" media="screen" href="/testGrid/Guriddo_jqGrid_JS_4_8_2/css/jquery-ui.css" />
<!-- The link to the CSS that the grid needs -->
<link rel="stylesheet" type="text/css" media="screen" href="/testGrid/Guriddo_jqGrid_JS_4_8_2/css/trirand/ui.jqgrid.css" />
<style type="text/css">
.ui-jqgrid .ui-jqgrid-bdiv { overflow-y: scroll;}
th.ui-th-column div {
/* see http://stackoverflow.com/a/7256972/315935 for details */
word-wrap: break-word; /* IE 5.5+ and CSS3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: pre-wrap; /* CSS3 */
overflow: hidden;
height: auto !important;
vertical-align: middle;
}
.ui-jqgrid tr.jqgrow td {
white-space: normal !important;
height: auto;
vertical-align: middle;
padding-top: 2px;
padding-bottom: 2px;
}
.ui-jqgrid .ui-jqgrid-htable th.ui-th-column {
padding-top: 2px;
padding-bottom: 2px;
}
.ui-jqgrid .frozen-bdiv, .ui-jqgrid .frozen-div {
overflow: hidden;
}
</style>
</head>
<body>
<table id="list"><tr><td /></tr></table>
<script type="text/ecmascript" src="/testGrid/Guriddo_jqGrid_JS_4_8_2/js/jquery.min.js"></script>
<script type="text/ecmascript" src="/testGrid/Guriddo_jqGrid_JS_4_8_2/js/jquery-ui.min.js"></script>
<script type="text/ecmascript" src="/testGrid/Guriddo_jqGrid_JS_4_8_2/js/trirand/i18n/grid.locale-en.js"></script>
<script type="text/ecmascript">
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;
</script>
<!--script type="text/javascript" src="/testGrid/jqGrid-master/jqGrid-master/js/jquery.jqGrid.js"></script-->
<script type="text/javascript" src="/testGrid/Guriddo_jqGrid_JS_4_8_2/js/trirand/jquery.jqGrid.min.js"></script>
<script type="text/javascript">
//<![CDATA[
/*global $ */
/*jslint unparam: true */
$(function () {
$(document).ready(function () {
$grid = $("#list"),
resizeColumnHeader = function () {
var rowHight, resizeSpanHeight,
// get the header row which contains
headerRow = $(this).closest("div.ui-jqgrid-view")
.find("table.ui-jqgrid-htable>thead>tr.ui-jqgrid-labels");
// reset column height
headerRow.find("span.ui-jqgrid-resize").each(function () {
this.style.height = '';
});
// increase the height of the resizing span
resizeSpanHeight = 'height: ' + headerRow.height() + 'px !important; cursor: col-resize;';
headerRow.find("span.ui-jqgrid-resize").each(function () {
this.style.cssText = resizeSpanHeight;
});
// set position of the dive with the column header text to the middle
rowHight = headerRow.height();
headerRow.find("div.ui-jqgrid-sortable").each(function () {
var $div = $(this);
$div.css('top', (rowHight - $div.outerHeight()) / 2 + 'px');
});
},
fixPositionsOfFrozenDivs = function () {
var $rows;
if (this.grid.fbDiv !== undefined) {
$rows = $('>div>table.ui-jqgrid-btable>tbody>tr', this.grid.bDiv);
$('>table.ui-jqgrid-btable>tbody>tr', this.grid.fbDiv).each(function (i) {
var rowHight = $($rows[i]).height(), rowHightFrozen = $(this).height();
if ($(this).hasClass("jqgrow")) {
$(this).height(rowHight);
rowHightFrozen = $(this).height();
if (rowHight !== rowHightFrozen) {
$(this).height(rowHight + (rowHight - rowHightFrozen));
}
}
});
$(this.grid.fbDiv).height(this.grid.bDiv.clientHeight);
$(this.grid.fbDiv).css($(this.grid.bDiv).position());
}
if (this.grid.fhDiv !== undefined) {
$rows = $('>div>table.ui-jqgrid-htable>thead>tr', this.grid.hDiv);
$('>table.ui-jqgrid-htable>thead>tr', this.grid.fhDiv).each(function (i) {
var rowHight = $($rows[i]).height(), rowHightFrozen = $(this).height();
$(this).height(rowHight);
rowHightFrozen = $(this).height();
if (rowHight !== rowHightFrozen) {
$(this).height(rowHight + (rowHight - rowHightFrozen));
}
});
$(this.grid.fhDiv).height(this.grid.hDiv.clientHeight);
$(this.grid.fhDiv).css($(this.grid.hDiv).position());
}
},
fixGboxHeight = function () {
var gviewHeight = $("#gview_" + $.jgrid.jqID(this.id)).outerHeight(),
pagerHeight = $(this.p.pager).outerHeight();
$("#gbox_" + $.jgrid.jqID(this.id)).height(gviewHeight + pagerHeight);
gviewHeight = $("#gview_" + $.jgrid.jqID(this.id)).outerHeight();
pagerHeight = $(this.p.pager).outerHeight();
$("#gbox_" + $.jgrid.jqID(this.id)).height(gviewHeight + pagerHeight);
};
// Define the grid
$("#list").jqGrid({
datatype: 'local',
//data: mydata,
colNames: ['Country', 'State', 'City', 'Attraction', 'longText', 'Zip code'],
colModel: [
{ name: 'country', width: 170, align: 'center', frozen: true, cellattr: arrtSetting, title:false},
{ name: 'state', width: 180, align: 'center', frozen: true},
{ name: 'city', width: 190 },
{ name: 'attraction', width: 120 },
{ name: 'longText', width: 80000 },
{ name: 'zip', index: 'tax', width: 160, align: 'right' }
],
cmTemplate: {sortable: false},
rowNum: 100,
//rowList: [5, 10, 20],
//pager: '#pager',
gridview: true,
hoverrows: false,
autoencode: true,
ignoreCase: true,
viewrecords: true,
loadComplete: updateSize,
resizeStop: updateSize,
//height: '100%', width: null, shrinkToFit: false,
height: '80', width: null, shrinkToFit: false,
caption: 'Grid with rowSpan attributes',
beforeSelectRow: function () {
return false;
}
});
$grid = $("#list")
jQuery("#list").jqGrid('setFrozenColumns');
$grid.jqGrid('gridResize', {
minWidth: 450,
stop: function () {
fixPositionsOfFrozenDivs.call(this);
fixGboxHeight.call(this);
},
loadComplete: function () {
fixPositionsOfFrozenDivs.call(this);
}
});
$grid.bind("jqGridResizeStop", function () {
resizeColumnHeader.call(this);
fixPositionsOfFrozenDivs.call(this);
fixGboxHeight.call(this);
});
// resizeColumnHeader.call($grid[0]);
// //$grid.jqGrid('setFrozenColumns');
// $grid.triggerHandler("jqGridAfterGridComplete");
// fixPositionsOfFrozenDivs.call($grid[0]);
// Data to be sent from various sources and aggregated...
var someLongText = "1111111111111111111111111111111111111111111111098888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww55555555555555555555555555555555555555555555555jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjsdfaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj4324333333333333333333333333333333333333333333333333333333333333333333333333333333555555555555555555555555555555555555555555555gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxlllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllpppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd";
var mydata = [
{ country: "USA", state: "Texas", city: "Houston", attraction: "NASA", longText: someLongText, zip: "77058" , attr: {country: {rowspan: "9"}} },
{ country: "USA", state: "Texas", city: "Austin", attraction: "6th street", zip: "78704", attr: {country: {display: "none"}} },
{ country: "USA", state: "Texas", city: "Arlinton", attraction: "Cowboys Stadium", zip: "76011" , attr: {country: {display: "none"}} },
{ country: "USA", state: "Texas", city: "Plano", attraction: "XYZ place", zip: "54643" , attr: {country: {display: "none"}} },
{ country: "USA", state: "Texas", city: "Dallas", attraction: "Reunion tower", zip: "12323" , attr: {country: {display: "none"}} },
{ country: "USA", state: "California", city: "Los Angeles", attraction: "Hollywood", zip: "65456", attr: {country: {display: "none"}} },
{ country: "USA", state: "California", city: "San Francisco", attraction: "Golden Gate bridge", zip: "94129" , attr: {country: {display: "none"}} },
{ country: "USA", state: "California", city: "San Diego", attraction: "See world", zip: "56653" , attr: {country: {display: "none"}} },
{ country: "USA", state: "California", city: "Anaheim", attraction: "Disneyworld", zip: "92802" , attr: {country: {display: "none"}} }
];
// Populate grid
for (var i = 0; i < mydata.length; i++) {
$("#list").jqGrid('addRowData', "myId_" + i, mydata[i], "last");
}
resizeColumnHeader.call($grid[0]);
//$grid.jqGrid('setFrozenColumns'); Already did this.
$grid.triggerHandler("jqGridAfterGridComplete");
fixPositionsOfFrozenDivs.call($grid[0]);
});
arrtSetting = function (rowId, val, rawObject, cm) {
var attr = rawObject.attr[cm.name];
var result;
if (attr.rowspan) {
result = ' rowspan=' + '"' + 9 + '"';
}
if (attr.display) {
result = ' style="display:' + attr.display + '"';
}
result = result + ' title=" this is the tooltip for ' + rowId + '"';
return result;
};
function updateSize(){
//getting all lines in two tables by they id
var lines = $("tr", this),
flines = $("tr", "#"+$(this).attr("id")+"_frozen" );
//setting in all frozen lines height equel to grid
flines.each(function(i, item){
//i%2 check because of border collapse
$(item).height( $(lines[i]).innerHeight() - (i%2?1:0) );
});
};
});
//]]>
</script>
</body>
</html>

Custom template column does not work in JQGrid

Experts,
I have JQGrid with custom template column like Edit. the following screen display data without Edit link in last column.
Javascript code:
<script language="javascript" type="text/javascript">
function editFmatter(cellvalue, options, rowObject) {
var cellHtml = "<a href='#' originalValue='" + cellvalue + "'>" + cellvalue + "</a>";
return cellHtml;
}
function unformatEdit(cellvalue, options) {
return $(cellObject.html()).attr("originalValue");
}
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Action("JQGridGetGridData", "TabMaster")',
datatype: 'json',
mtype: 'GET',
colNames: ['col ID', 'First Name', 'Last Name', 'Edit'],
colModel: [
{ name: 'colID', index: 'colID', width: 100, align: 'left', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{ name: 'FirstName', index: 'FirstName', width: 150, align: 'left', editable: true },
{ name: 'LastName', index: 'LastName', width: 150, align: 'left', editable: true },
{ name: 'Edit', index: 'Edit', width: 80, align: "center", editable: true, formatter: editFmatter, unformat: unformatEdit }
],
pager: jQuery('#pager'),
rowNum: 100,
rowList: [10, 50, 100, 150],
sortname: 'colID',
sortorder: "asc",
viewrecords: true,
multiselect: true,
imgpath: '#Url.Content("~/Scripts/themes/steel/images")',
caption: 'Tab Master Information'
}).navGrid('#pager', { edit: true, add: true, del: true },
// Edit options
{
savekey: [true, 13],
reloadAfterSubmit: true,
jqModal: false,
closeOnEscape: true,
closeAfterEdit: true,
url: '#Url.Action("JQGridEdit", "TabMaster")',
afterSubmit: function (response, postdata) {
if (response.responseText == "Success") {
jQuery("#success").show();
jQuery("#success").html("Record updated successfully! [" + postdata.FirstName + " " + postdata.LastName + "]");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
// Add options
{
url: '#Url.Action("JQGridCreate", "TabMaster")',
closeAfterAdd: true,
afterSubmit: function (response, postdata) {
if (response.responseText == "Success") {
jQuery("#success").show();
jQuery("#success").html("Record added successfully! [" + postdata.FirstName + " " + postdata.LastName + "]");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
// Delete options
{
url: '#Url.Action("JQGridRemove", "TabMaster")',
afterSubmit: function (response, rowid) {
if (rowid.length > 0) {
jQuery("#success").show();
jQuery("#success").html("Record deleted successfully! [" + rowid + "]");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
{
closeOnEscape: true,
multipleSearch: false,
closeAfterSearch: true
}
);
});
</script>
#using (Html.BeginForm())
{
<p>
#Html.ActionLink("Create New", "Create") | #Html.ActionLink("Bulk Insert", "AddList")
#* | #Html.ActionLink((string)ViewBag.RemoveSelectedTitle, "RemoveSelected")*#
</p>
<table id="list" class="scroll" cellpadding="0" cellspacing="0" width="100%">
</table>
<div id="pager" class="scroll" style="text-align: center;">
</div>
<div id="success" style="color: Green">
</div>
Controller.cs
public JsonResult JQGridGetGridData(string sidx, string sord, int rows, int page)
{
int totalRecords = Convert.ToInt32(_tabmasterService.Count());
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
IQueryable<TabMasterViewModel> tabmasters = _tabmasterService.GetQueryTabMasterList(sidx, sord, rows, page);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from tm in tabmasters
select new
{
id = tm.colID,
cell = new string[] { tm.colID.ToString(), tm.FirstName, tm.LastName, "Edit" }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
First of all I would recommend you to take a look in this and this answers which shows how you can implement Edit links in the jqGrid.
Your current code have some problems:
In the unformatEdit you forgot to define the third parameter cellObject and use undefined value.
It's not good to add attributes like originalValue which are not corresponds to HTML standards. If you do need to extend attributes you should use data- prefix in the attribute name to be HTML5 compliant. In the case you can change the code to $(cellObject).children('a:first').attr("data-originalValue"); for example.
It is not good to define global functions because of possible name conflicts. You can move declaration of the function inside of jQuery(document).ready(function () {/*here*/}); event handler. You can define the function like a variables: var editFmatter = function(cellvalue, options, rowObject) {/* the body of the function*/}; and use later in the same way like you did as before.
You should use the last version of jqGrid (currently 4.1.1). Many parameters like imgpath which you use are not exist since years (see here). If you look for more recent ASP.NET MVC code example I would recommend you take a look in the "UPDATED" part of the answer and download the corresponding code examples (the VS2008 project and the VS2010 project).
I have solved question from myself.
I have done following:
{ name: 'Edit', index: 'Edit', width: 80, align: 'center', editable: false, formatter: editFmatter, unformat: unformatEdit }
and
function editFmatter(el, cellval, opts) {
var editHTML = "<img src='Images/row_edit.gif' alt='Edit' title='Edit' onclick='openEditDialog(" + opts.rowId + ");'>";
var deleteHTML = "<img src='Images/row_delete.gif' alt='Delete' title='Delete' onclick='openDeleteDialog(" + opts.rowId + ");'>"; ;
var finalHTML = editHTML + " " + deleteHTML;
$(el).html(finalHTML);
}
function unformatEdit(cellvalue, options) {
//return $(el).html().attr("originalValue");
}
Thanks,
Imdadhusen

Resources