Formatting a cell of GridPanel is straight forward in ExtJS. However API documentation was not very straight forward so I thought it will be helpful for others to use the example below:
Suppose you have a grid with following configuration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var doctorSearchGrid = new Ext.grid.GridPanel({ frame:false, title: 'Doctor search result', autoHeight:true, height : 'auto', width:700, footer : true, store: doctorSearchStore, columns: [ {header: "Country", dataIndex: 'country'}, {header: "hospital", dataIndex: 'hospital'}, {header: "male doctors", dataIndex: 'male_doctor_count'} {header: "female doctors", dataIndex: 'female_doctor_count'} ] }); |
If the male and female count ratio in a given hospital is greater than 1.2 then we want to show the female count in RED color. If the ratio is less than .80 then we want to show the female count in GREEN color.
How do we do that?
If you notice, in above code, columns configuration is an array of type ColumnModel. ColumnModel provides a configuration renderer, which allows you to specify a function, which is used to generate HTML markup for a cell given the cell’s data value.
1 2 3 4 5 6 7 8 9 10 11 12 13 | function formatFemaleCount( currentCellValue, metadata, record, rowIndex, colIndex, doctorOrderStore ) { var docRecords = doctorOrderStore.getAt(rowIndex); var maleFemaleRatio = docRecords.male_doctor_count / docRecords.female_doctor_count; if ( maleFemaleRatio <= .80 ) { metadata.attr = 'style="color:green;"'; } else if ( maleFemaleRatio >= 1.2 ) { metadata.attr = 'style="color:red;"'; } else { metadata.attr = 'style="color:black;"'; } return currentCellValue; } |
You can even change the display value by returning the desired value.
I observed that if you do not return a value, it starts showing empty value in the cell. It was a bit surprising because documentation doesn’t say anything about returning a value.
Finally, you need to define the renderer attribute for the desired cell.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var doctorSearchGrid = new Ext.grid.GridPanel({ frame:false, title: 'Doctor search result', autoHeight:true, height : 'auto', width:700, footer : true, store: doctorSearchStore, columns: [ {header: "Country", dataIndex: 'country'}, {header: "hospital", dataIndex: 'hospital'}, {header: "male doctors", dataIndex: 'male_doctor_count'} {header: "female doctors", dataIndex: 'female_doctor_count', renderer:formatFemaleCount } ] }); |
You can even use Ext.util.Format methods as renderer. In fact, usually, that should be sufficient for your need.