Monday, June 20, 2011

How to show image or checkbox html component in extjs grid column header ?

There can be an use case where an image needs to be shown within certain extjs grid column heder.
Also you might want to show some html components within specific grid column header. This can be achieved by reseting the grid column header after the grid is being rendered. To achieve this you need to add afterrender listener and within it you would need to reset the grid column header. To reset the grid header, you need to get the grid view first and then get the specific column by calling view.getHeaderCell(columnIndex) method and then replace its innerHTML.
Example:
In below example, I am adding the image to a column with id "imageColumn" and a checkbox to a column with id "checkboxColumn". Also I am adding a mandatory flag to identify the fields which are mandatory.
var myGrid = new Ext.grid.GridPanel({
    id: 'demo-grid-header-img-grid',
    layout: 'fit',
    store: gridHeaderStore, // replace it with your custom store.
    cm: gridHeaderColumnModel, // replace it with your custom column model.
    listeners: {
        afterrender: function(_grid){
            var columns = _grid.getColumnModel().config;
            var view = _grid.getView();
            var columnIndex = 0;
            Ext.each(columns, function(column){
                var headerHtml = '<div class="x-grid" + columnIndex + '-hd-inner x-grid' + columnIndex + '-hd-' + column.id + '" unselectable="on" style="">' + column.header;
                // To show mandatory column flag
                headerHtml += '&nbsp;<font color=red>*</font>
                /*column id starting with "imageColumn" text. You can also use column.id == "imageColumn" or your column id*/
                if(column.id.match("^" + "imageColumn")) {
                    headerHtml += '&nbsp;<img src="/images/headerImage.jpg" width=12 height=12>';
                }
                //To add checkbox to specific column header
                else if(column.id.match("^" + "checkboxColumn")){
                    headerHtml += '&nbsp;<input type="checkbox" id="'+column.header+'chk" onclick="javascipt:headerChkHandler()">';
                }
                headerHtml += '</div>';
                //replace the view headerCell innerHTML.
                view.getHeaderCell(columnIndex).innerHTML = headerHtml;
                columnIndex = columnIndex + 1;
            });
        }
    }
});

Note : if enableColumnMove is not disabled for your grid then you would also need to listen 'columnMove' event and repeat the same process there as well.

No comments:

Post a Comment