i am using jqGrid treegrid and i want to format the back color of columns based on the value of the data in the cell (its an integer):
Here is an example where I setup the column:
{
name: 'missingBooks',
cellattr: function (rowId, tv, rawObject, cm, rdata) {
//conditional formatting
if (rawObject[11] > 0) {
return 'style="background-color:#FFCCCC"';
}
},
width: 75,
unformat: originalValueUnFormatter,
formatter: missingBooksFormatter,
align: "right",
index: 'missingBooks',
hidden: false,
sorttype: 'int',
sortable: true
},
this works fine but my issue is in the cellAttr callback. In this conditional formatting line:
if (rawObject[11] > 0) {
return 'style="background-color:#FFCCCC"';
}
i would like to reuse this logic so i dont want to have to index into the rawObject and figure out what column i am using. i was hoping there was a way to do something like this:
if (rawObject.missingBooks > 0) {
return 'style="background-color:#FFCCCC"';
}
but this seems to be undefined. This way if i add a new column i dont have to reindex all of this conditional formatting code.
I understand the problem. I suggested Tony to make some changes in jqGrid code. Mostly it would be enough to modify the place in the code to fill first rd
and then in the next for loop call addCell
with rd
as additional parameter. The function addCell
could forward the information to formatCol
and the formatCol
can call cellattr
with additional parameter rd
which will be has the information in exact the same format like you as want.
Nevertheless one can relatively easy to have almost the same results which you need without any changes in the jqGrid code. To do this one can just construct the map object which can give us the index of the column in the rawObject
based on the name.
For example we can use beforeRequest
or beforeProcessing
to fill the map if it is not yet filled. The code can looks like
var colMap = {};
$("#tree").jqGrid({
...
colModel: [
{name: 'missingBooks',
cellattr: function (rowId, tv, rawObject, cm, rdata) {
//conditional formatting
if (Number(rawObject[colMap.missingBooks]) > 0) {
return ' style="background-color:#FFCCCC"';
} else {
return '';
}
}
...
],
beforeRequest: function () {
if ($.isEmptyObject(colMap)) {
var i, cmi,
cm = $(this).jqGrid('getGridParam', 'colModel'),
l = cm.length;
for (i = 0; i < l; i++) {
cmi = cm[i];
colMap[cmi.name] = i;
}
}
}
});
So the code will be free from usage of indexes like rawObject[11]
where the index 11
can be changed after some modification in the code.
You can see the corresponding demo here.