Saturday, 8 March 2014

Ext JS Grid Application using MVC architecture

What this post will teach you?
  • The structure of folders when following MVC pattern in Ext JS
  • How to create a view?
  • How to create a model with proxy and a custom field?
  • How to create a store and populate using JSON data?
  • How to bind a store to a grid?
Output of this tutorial

So let's start.
How to begin?
  • You need a notepad to write the code. 
  • You also need Ext JS libraries. Ask Google for help.
  • I am running this on Apache Tomcat using XAMPP
Folder Structure (Which file goes where?)

Starting with the html file which will have references to
  • Ext JS package
  • CSS and
  • app.js (the start point for our Ext JS applicatio)
Index.html
<!DOCTYPE html>
<html>
<head> 
 <title>Ex JS Grid Application (MVC)</title>
 <script src = "ext-all.js"></script>
 <script src = "app.js"></script>
 <link rel="stylesheet" type="text/css" href="ext-all.css">
</head>
<body>
</body>
</html>

Now we define app.js.
Ext.application(
{
 appFolder  : 'app', //default
 name  : 'Example', 
 controllers :
 [
  'Example.controller.grid.StockGrid'
 ], 
 autoCreateViewport : true
});
As autoCreateViewport is set to true, it will automatically go to view folder, look for Viewport.js and renders the application. What is a Viewport? Google, you will get it. I do not want to reinvent the same wheel.

This file first goes to controller and executes the controller and then comes to Viewport. We will see the Viewport code  next and then will have a look at the controller and files referred inside it.

Viewport.js
Ext.define('Example.view.Viewport',
{
 extend : 'Ext.container.Viewport',
 layout : 'border',
 
 requires :
 [
  'Example.view.grid.StockGrid'
 ],
 
 initComponent : function()
 {
  var me = this;
  me.items = me.getComponents();
  me.callParent();
 },
 
 getComponents : function()
 {
  return(
  [
   {
    xtype : 'stock-grid',
    region : 'center'
   } 
  ]);
 }
});

JSON Data -> stockdata.json
{
    "response": "success",
    "stocklist": [
        {
            "name": "Maruti Suzuki India Ltd.",
            "code": "maruti",
            "ltp": "1586.30",
            "high": "1864.00",
            "low": "1217.00"
        },
        {
            "name": "Reliance Industries Ltd.",
            "code": "reliance",
            "ltp": "799.25",
            "high": "927.90",
            "low": "765.00"
        },
        {
            "name": "Reliance Communications Ltd.",
            "code": "rcom",
            "ltp": "112.05",
            "high": "164.45",
            "low": "50.25"
        }
    ]
}

Model -> Stock.js
Ext.define('Example.model.Stock', {
    extend: 'Ext.data.Model',
    fields   : [
           {name : 'name',          type : 'string'},
           {name : 'code',    type : 'string', convert : function(value) {return value.toUpperCase();}},
           {name : 'ltp',   type : 'numeric'},
     {name : 'high',   type : 'numeric'},
     {name : 'low',   type : 'numeric'},
     {name : 'avg', type:  'numeric', convert : function(value, record) 
 {
  var high  = parseInt(record.get('high'));
  var ltp  = parseInt(record.get('ltp'));
  var low  = parseInt(record.get('low'));
  return ((high+low+ltp)/3);
 },  defaultValue : 'NA'}
    ],
 
 proxy: 
 {
        type: "ajax",
        url: "app/data/stockdata.json",  
        reader: {
            type    : 'json',
            root    : 'stocklist'
        }
    } 
});

Store -> Stocks.js
Ext.define('Example.store.Stocks',
{
 extend  : 'Ext.data.Store',
 requires : ['Example.model.Stock'], 
 model  : 'Example.model.Stock', 
 autoLoad : false
});

View -> StockGrid.js
Ext.define('Example.view.grid.StockGrid',
{
 extend : 'Ext.grid.Panel',
 alias : 'widget.stock-grid',
 title : 'BSE Stock List',
  
 requires:
  [
   'Example.store.Stocks'
  ],
  
 store : 'Stocks',
 columns : [
  {
   header  : 'Stock Name',
   dataIndex : 'name',
   flex  : 2
  },
  
  {
   header  : 'Stock Code',
   dataIndex : 'code',
   flex  : 1
  },
   
  {
   header  : 'Last Trade Price',
   dataIndex : 'ltp',
   flex  : 1,
   renderer: Ext.util.Format.numberRenderer('0.000')
  },
   
  {
   header  : '52 Week High',
   dataIndex : 'high',
   flex  : 1,
   renderer: Ext.util.Format.numberRenderer('0.000')
  },
    
  {
   header  : '52 Week Low',
   dataIndex : 'low',
   flex  : 1,
   renderer: Ext.util.Format.numberRenderer('0.000')
  },
    
  {
   header  : 'Average',
   dataIndex : 'avg',
   renderer: Ext.util.Format.numberRenderer('0.000')
  }
 ],
 
 initComponenet : function()
 {
  var me = this;  
  me.callParent();
 }
});

Controller -> StockGrid.js
Ext.define('Example.controller.grid.StockGrid',
{
 extend : 'Ext.app.Controller',
 
 views : [ 'grid.StockGrid'],
 
 models: ['Stock'],
 
 stores : ['Stocks'],
 
 init : function()
 {
  var me = this;
  me.bindListeners();
  me.callParent(); 
 },
 
 bindListeners : function()
 {
  var me = this;
 
  this.control(
   {
    'stock-grid' :
    {
     render : me.loadStockStore
    }
   }
  ); 
 },
  
 loadStockStore : function()
 {
  var me = this;
  me.getStocksStore().load();
 } 
});

Ensure that your application is supported by Internet Explorer.

Download Link
Click here to download this project.

What next?
We will connect this grid to a MySQL table using PHP and will populate data from there rather than populating from the static JSON data file.



Reference
If you want to know anything about Ext JS, hit the docs link.

If you are facing difficulty in understanding the code, you can comment to this post.

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.