The bast way to implement "virtual columns" in jqGrid is the usage of the custom formatter. For example
{name:'amount',index:'amount',width:70, formatter:'currency', align:'right'},
{name:'tax',index:'tax',width:50, formatter:'currency', align:'right'},
{name:'total',index:'total',width:60, align:'right',
formatter:function(cellvalue, options, rowObject) {
var amount = parseInt(rowObject.amount,10),
tax = parseInt(rowObject.tax,10);
return $.fmatter.util.NumberFormat(amount+tax,$.jgrid.formatter.currency);
}}
The main disadvantage of the usage of the custom formatter is that you use make full formatting inside. The call of the method $.fmatter.util.NumberFormat
can help us to simplify the work.
If you use remote datatype (datatype: 'xml'
or datatype: 'json'
) the server is responsible for data sorting. So the server should be able to sort the data not only for the "real" data field but for the "virtual" columns also. We use index:'total'
above. So if the user click on the header of the 'Total' column the sidx
parameter which will be send to the server will be total
. So the server should be able to produce the data sorted by the total
.
If you use local data you can use sorttype
as the function to implement the sorting:
{name:'amount',index:'amount',width:70, formatter:'currency', sorttype:'number',
align:'right'},
{name:'tax',index:'tax',width:50, formatter:'currency', sorttype:'number',
align:'right'},
{name:'total',index:'total',width:60, align:'right',
formatter:function(cellvalue, options, rowObject) {
var amount = parseInt(rowObject.amount,10),
tax = parseInt(rowObject.tax,10);
return $.fmatter.util.NumberFormat(amount+tax,$.jgrid.formatter.currency);
},
sorttype:function(cellvalue, rowObject) {// like for sorttype:'number',
var amount = parseInt(rowObject.amount,10),
tax = parseInt(rowObject.tax,10);
return amount+tax;
}}
See the demo here.