Almost three years ago I wrote a blog entry on doing custom grid renderers with CFGRID and the Ext grid for ColdFusion 8. This week a reader and I went back and forth in the comments concerning how to build a renderer that would modify a column but check other column values for the logic. So for example, in that previous blog entry my logic for a custom product column was to check to see if the product was "Product 4". What if I wanted to check the price for example? Here is an updated version that works with ColdFusion 9 and does just that.

<cfajaximport/> <html>

<head> <script>

myf = function(data,cellmd,record,row,col,store) { console.dir(record.data); //old logic, prod 4 only //if(data == "Product 4") return "<b style='color:red'>" + data + "</b>"; //new logic, price > 50 and type is weapon if(record.data.TYPE == 'weapon' && record.data.PRICE > 50) return "<b style='color:red'>" + data + "</b>"; else return data; } testgrid = function() { mygrid = ColdFusion.Grid.getGridObject('data'); cm = mygrid.getColumnModel(); cm.setRenderer(0, Ext.util.Format.usMoney); cm.setRenderer(1,myf); mygrid.reconfigure(mygrid.getStore(),cm); } </script> </head>

<body>

<cfset data = queryNew("price,product,type")> <cfloop from=1 to=10 index="x"> <cfset total = randRange(20,100) & "." & randRange(1,99)> <cfset product = "Product #X#"> <cfset queryAddRow(data)> <cfset querySetCell(data, "price", total+0, x)> <cfset querySetCell(data, "product", product, x)> <cfset querySetCell(data, "type", "#randRange(0,1)?'weapon':'fruit'#")> </cfloop>

<cfform name="test"> <cfgrid autowidth="true" name="data" format="html" query="data" width="600"> <cfgridcolumn name="price" header="Price"> <cfgridcolumn name="product" header="Product"> <cfgridcolumn name="type" header="Type"> </cfgrid> </cfform>

<cfset ajaxOnLoad("testgrid")> </body> </html>

If you compare this code to the older entry, the changes are:

  • In my fake query, I added a new type column. All my products are either weapons or fruits. (Although one could argue that you could turn some weapons into fruits. I mean turn some fruits into weapons. Yeah, that's it.)
  • Next look at the myf function. I kept the old logic in there commented out. You can see it made use of the data argument which is the cell being formatted. I ignore that though and check the rest of the row. This is passed in the record object. As you see, I check the TYPE and PRICE, and based on my business rule, I color the item red.
  • One small other change - back in the testgrid function (which remember is run when the application starts up), I changed getDataSource to getStore. This reflects the fact that the Grid used in CF9 has a different API then the one run in CF8.

If you want to see a demo of this, just hit the button below. You may need to reload once or twice since the values are random.