Continuing my work on custom components in Ext JS4, let’s create a custom grid component. This component takes up JSON data and displays it in a tabular format.
The component is used as shown below
{ xtype : "mygrid", fields : ["name","age"], data : [{name:"Sam",age:12},{name:"Ram",age:22}] }
The MyGrid component is shown below. The complicated part of the class is the XTemplate instance. The class is shown below.
Ext.define("DuraSoft.custom.MyGrid",{ extend : "Ext.Component", requires: ['Ext.XTemplate'], xtype : "mygrid", padding : 20, tpl : new Ext.XTemplate( '<table border="2">', '<thead><tr>', '<tpl for="fields">', '<th>{[this.formatHeader(values)]}</th>', '</tpl>', '</tr></thead><tbody>', '<tpl for="data">', '<tr>{[this.cells(values)]}</tr>', '</tpl>', '</tbody></table>', { formatHeader : function(val){ return val[0].toUpperCase()+val.substring(1,val.length); }, cells : function(obj){ var cells = ""; for(var i in obj){ cells += "<td>" + obj[i] + "</td>"; } return cells; } } ), initComponent : function(){ this.data = { fields : this.fields, data : this.data }; this.callParent(arguments); } });
The XTemplate constructs a table element, using fields and data. The XTemplate has two functions formatHeader and cells to format the header and data.