I am using a custom formatter for my jqGrid columnModel and I can’t get sorting to work with formatter functions. If I remove formatter column sorts normally.
jQuery("#listAgentOptions").jqGrid({
height: 240,
datatype: "local",
colNames: [' ', 'First Name', 'Last Name', 'Role'],
colModel: [
{ name: 'status', index: 'status', width: 18, sorttype: 'text', align: 'center', formatter: function(cellvalue, options, rowObject) {
return cellvalue == 1 ? "<img src='images/agent_green_s.png' alt='Ready' title='Ready' />" :
cellvalue == 3 ? "<img src='images/agent_red_s.png' alt='Busy' title='Busy' />" :
"<img src='images/agent_orange_s.png' alt='Pending Ready' title='Pending Ready' />";
},
unformat:
function(cellvalue, options, rowObject) { return Math.floor(Math.random() + 0.1).toString(); }
},
{ name: 'firstName', index: 'firstName', width: 92 },
{ name: 'lastName', index: 'lastName', width: 142 },
{ name: 'role', index: 'role', sorttype: 'int', width: 36, align: 'center', formatter: function(cellvalue, options, rowObject) {
return cellvalue == true ? "<img src='images/user_gray.png' alt='Supervisor' title='Supervisor' />" : "<img src='images/user.png' alt='Agent' title='Agent' />";
}, unformat:
function(cellvalue, options, rowObject) { return cellvalue; }
}
],
sortname: 'lastName'
});
Rows are added like this:
jQuery("#listAgentOptions").jqGrid('clearGridData');
$.each(result, function(i, item) {
if (item.ContactType == 1) {
jQuery("#listAgentOptions").jqGrid('addRowData', i+1, { firstName: item.ContactName.split(" ")[0], lastName: item.ContactName.split(" ")[1],
role: item.IsSupervisor,
status: item.Status == "Ready" ? 1 : item.Status == "Busy" ? 3 : 2
});
}
});
How do I get sorting to work properly?
Update. I have just downloaded the latest version of jqGrid – same issue.
I have also tried using unformat: function(cellvalue, options, rowObject) { } but cellvalue is empty there :-E When I use return Math.floor(Math.random() + 0.1).toString(); it does sort things randomly (each time I click), but return cellvalue; just returns an empty string.
OK, I have figured out what’s going on.
First of all you have to use
unformatto pass the initial value back to jqGrid sort function.jqGrid is passing
$(row).text()tounformatfunction, which for cells with just an html tag returns an empty string, and there is no option to change it. However, what you can do is use the third parameter ofunformatfunction, which in my case isrowObject. You can then retrieve the actual cell value by using$(rowObject).html()and parse it back to the value. Sorting will now work.Another thing to remember is that if you are using
sorrtype: 'int'you will have to return integer as a string, likereturn '1';.