Learning Ext JS 3

Binding information from an array to a grid Más videos

Descripción del tema

One of the most interesting components from ExtJS are the grids, which provide us the ability to display information in a simple and orderly way. In this tutorial we will learn how to use the components of a basic GridPanel such as DataStore (or data repository), ColumnModel, and SelectionModel.

Packaging the tutorial

Let's package the code first, to avoid conflicts with other variables.
Ext.ns('com.quizzpot.tutorial');   
  
Ext.BLANK_IMAGE_URL = '../ext-3.0/resources/images/default/s.gif';   
  
com.quizzpot.tutorial.ArrayGridTutorial = {   
    init: function(){   
        //The code of the tutorial goes here
    }
}   

Ext.onReady(com.quizzpot.tutorial.ArrayGridTutorial.init,com.quizzpot.tutorial.ArrayGridTutorial);

The Store

The next thing we need to do is define the data repository, which is where we will retrieve the data, in this case we are going to work with static data stored in a two-dimensional array like this:
//Two-dimensional array
var myData = [
	['3m Co',71.72,0.02,0.03,'9/1 12:00am'],
	['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'],
	['Altria Group Inc',83.81,0.28,0.34,'9/1 12:00am'],
	['American Express Company',52.55,0.01,0.02,'9/1 12:00am'],
	['American International Group, Inc.',64.13,0.31,0.49,'9/1 12:00am'],
	['AT&T Inc.',31.61,-0.48,-1.54,'9/1 12:00am'],
	['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'],
	['Caterpillar Inc.',67.27,0.92,1.39,'9/1 12:00am']
];
Now, let's define an "Ext.data.ArrayStore" that will be responsible for reading the data array, in order to do this we need to set the reference name of the data column and the type of data it contains.
//creating the data repository
var store = new Ext.data.ArrayStore({
	fields: [
	   {name: 'company'},
	   {name: 'price', type: 'float'},
	   {name: 'change', type: 'float'},
	   {name: 'pctChange', type: 'float'},
	   {name: 'updated', type: 'date', dateFormat: 'n/j h:ia'}
	]
});
store.loadData(myData);
The attribute "name" defines the name by which we will reference the first data column, the column called "price" is a reference to the second column and so on. You can use the "type" attributes which defines the data type of the column, "dateFormat" defines the format of the columns that have a date format (see ExtJS API for more information).

The Grid

Now we are ready to create our grid by using the object "Ext.grid.GridPanel":
//Creating the object Ext.grid.GridPanel
var grid = new Ext.grid.GridPanel({
	title:'Company List',
	store: store,
	renderTo: document.body,
	columns: [
		{id:'company',header: "Company", width: 160, sortable: true, dataIndex: 'company'},
		{header: "Price", width: 75, sortable: true, dataIndex: 'price'},
		{header: "Change", width: 75, sortable: true, dataIndex: 'change'},
		{header: "% of change", width: 75, sortable: true, dataIndex: 'pctChange'},
		{header: "Updated", width: 85, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'updated'}
	],
	stripeRows: true,
	height:250,
	width:500        
});
The grids, as well as the forms and other components inherit from "Ext.Panel", this has already been seen in previous tutorials so I guess you will be familiar with this. The properties used are: "title": property inherited from the Ext.Panel class, it defines the title of the panel. "store": property that defines where the grid will get the data, (the Ext.data.ArrayStore defined previously). "renderTo": defines where the grid is going to be rendered, receives a reference of the id of a DOM object or DIV. "columns": defines the header of each column, in here the store date are associated through the property "name" defined in the store. "id": defines the id of the column. "header": defines the name displayed in the title of each column. "width": sets the width of the column. "sortable": boolean property that defines if we're going to allow the ordering of the data by clicking the column heading. "dataIndex": in here we define the value of the property "name" of the store, by doing this we associate the data of the column of the store with the column of the table. "renderer": with this property we can customize the data as shown in the column, I'll explain that later. "stripeRows": this property is used to show a slight shading spacing in the rows of the table. "height": defines the height of the grid. "width": define the width of the grid.
Image of a grid

Image of a basic grid

As we can see the grids have well-defined components, for the data management we need to use a store whose type depends on the type of information we need to handle; for example we have the "Ext.data.JSONStore" that handles information in JSON format, I suggest you to check the API to see more properties and types of data repositories.

The ColumnModel

Even though our grid is now ready and there are some things we might need that thankfully ExtJS has, one of those things are "Ext.grid.ColumnModel" which can be use to display the columns in the table and link them with the columns of the store, at the same time they provide functionalities such as selection of rows using a checkbox or a column for the enumeration of the rows. Basically, creating a columnModel is similar to the content we've added in the property "columns" of our table.
//Creating the object Ext.grid.ColumnModel
var myColumnModel = new Ext.grid.ColumnModel([
	{id:'company',header: "Company", width: 160, sortable: true, dataIndex: 'company'},
	{header: "Price", width: 75, sortable: true, dataIndex: 'price'},
	{header: "Change", width: 75, sortable: true, dataIndex: 'change'},
	{header: "% of change", width: 75, sortable: true, dataIndex: 'pctChange'},
	{header: "Updated", width: 85, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'updated'}
]);
//our grid will  be changed to associated with the variable myColumnModel
var grid = new Ext.grid.GridPanel({
	title:'Company List',
	store: store,
	renderTo: document.body,
	cm: myColumnModel,//reference to columnModel
	stripeRows: true,
	height:250,
	width:500        
});
Now let's number the rows and add a column of checkboxes for the selection.
//Creating the object Ext.grid.ColumnModel
var myColumnModel = new Ext.grid.ColumnModel([
  	new Ext.grid.RowNumberer(),
  	new Ext.grid.CheckboxSelectionModel(),
  	{id:'company',header: "Company", width: 160, sortable: true, dataIndex: 'company'},
  	...
]);
Image of a Grid

A grid with numeration on the rows and checkboxes to select them

The SelectionModel

We are almost done, the only thing to add is a "Ext.grid.SelectionModel" which will indicate the mode of selection that our grid will have.
//Creating a variable to link our object
var mySelectionModel = new Ext.grid.CheckboxSelectionModel({singleSelect: false});

//these are the settings we need for the grid
var grid = new Ext.grid.GridPanel({
	title:'Company List',
	store: store,
	renderTo: document.body,
	cm: myColumnModel, //reference of the columnModel
	sm: mySelectionModel, //reference of the selectionModel
	stripeRows: true,
	height:250,
	width:500        
});
Image of a grid

Characteristics of a grid in Ext JS

Conclusions

Today we have created a simple grid that reads data from an Array using an "ArrayStore", then we created the table and we associated the store columns with the property "columns" of the table or creating a "ColumnModel" and finally we added a "SelectionModel" to manage the way to select rows, soon we will learn how to use different types of store, use events in the store and the table and "selecionModel. If you have any question or suggestion feel free to leave a comment in this post. Don't forget to follow us on Twitter (@quizzpot) or add our feeds to your favorite RSS reader.

Te gustaría recibir más tutoriales como este en tu correo?

Este tutorial pertenece al curso Learning Ext JS 3, te recomiendo revises el resto de los tutoriales ya que están en secuencia de menor a mayor complejidad.

Si deseas recibir más tutoriales como este en tu correo te recomiendo registrarte al curso, si ya eres miembro solo identifícate y registrate al curso, si no eres miembro te puedes registrar gratuitamente!

Si no gustas registrarte en este momento no es necesario! Aún así puedes recibir los nuevos tutoriales en tu correo! Jamás te enviaremos Spam y puedes cancelar tu suscripción en cualquier momento.

¿Olvidaste tu contraseña?

Se el primero en comentar!

Instructor del curso

Crysfel3

Autor: Crysfel Villa

Software engineer with more than 7 years of experience in web development.

Descarga Código Fuente Ver Demostración

Regístrate a este curso

Este tutorial pertenece al curso Learning Ext JS 3, revisa todos los tutoriales que tenemos en este mismo curso ya que están en secuencia y van de lo más sencillo a lo más complicado.

Tendrás acceso a descargar los videos, códigos y material adicional.

Podrás resolver los ejercicios incluidos en el curso así como los Quizzes.

Llevarás un registro de tu avance.