Create Application using Ext Js

nutritionistcornInternet and Web Development

Dec 14, 2013 (3 years and 8 months ago)

133 views






Create Application using Ext Js

|

1






Create
Application using
Ext Js

By Dattu Dave













Create Application using Ext Js

|

2



1.

Getting All Required Resources


So these are the things we will develop, Now Let's start creating an application but before that
you should have following things to develop application in EXT
-

JS


I.
S
encha Command

-

http://www.sencha.com/products/sencha
-
cmd/download

II.
Java Sdk

-

http://www.oracle.com/techne
twork/java/javase/downloads/index.html

(it is
require to run sencha cmd properly)

III.

A web server

-

Xampp (
http://www.apachefriends.org/en/xampp.html
) we will use PHP as
server side code we use data
base from xampp


IV.

EXT JS

:
http://www.sencha.com/products/extjs/

(download Ext JS 4.x)


If you have all the above things in your pc, you can now start developing an application


First Extract the EXT JS
zip file you have downloaded from above url
,

we are here using Ext Js
4 for developing our application so
,

if you have any older version please download Ext Js 4.x
version from
http://www.sencha.com/pro
ducts/extjs/



After downloading zip file
extract the zip

file

into your servers root folder in our case we are
using
xampp

so extract inside
htdocs

folder
and rename it to extjs
.


2.

Creating an Application
structure
using Sencha Cmd


The next step is to us
e the Sencha Cmd to create the application
structure (MVC)
for us. To do
so, we need to open the
terminal

application that comes with the operating system we use. For
Linux and Mac OS users, it is the terminal application, and for Windows users, the
comman
d

prompt

application.


Now we need to change the current directory location in terminal or command prompt to Ext JS
directory (htdocs/extjs directory in this case), and then we will use the following command:
sencha generate app MyApp ../
result

as shown
in following screenshot:




Sencha generate command is use to create an
directory

structure of Ext Js for that you must
require a directory of
E
xt
J
s that’s why we change our current location in terminal to Ext Js


The directory structure of Ext Js follow
s MVC architecture,
MyApp

is the name of the
namespace of our application, meaning that every class we create is going to start with
MyApp
,
as for example:
MyApp
.model.Student
,
MyApp
.view.Result
, and so on. And the last argument
passed to the command is th
e directory where the application will be created. In this case it is
inside a folder named
result
, which is located inside the
htdocs
folder.







Create Application using Ext Js

|

3



So when we execute this command we get following output:





3.

Creating the loading page

Let's start with the hand
s
-
on now!

First, we need to edit th
e

result/
app.js

file. This is how the file looks like:

Ext.application({


name: 'MyApp',


views: [


'Main',


'Viewport'


],


controllers: [


'Main'


],


autoCreateViewport: true

});






Create Application using Ext Js

|

4



We are going to change it so that it looks like the following
(
result/
app.js
)
:

Ext.application({



name: 'MyApp',




launch: function() {


console.log('launch');


}

});



On first line of the previous code we have the
Ext.application

d
eclaration. This means that our
application will have a single page and the parent container of the app will be the Viewport. The
Viewport is a specialized container representing the viewable application area that is rendered
inside the
body

tag of the HTM
L page (
<
body></body>
).

It also manages the application's size
inside the browser and manages the window resizing.


Inside
Ext.application

we can also declare
models, views, stores, and controllers

used by the
application. We will add this information to t
his file as we create new classes for our project.

We need to declare the name of the application “
MyAPP
” which will be the

namespace
.


We can also create a
launch function

inside
Ext.application
. This function will be called after
all the application's co
ntrollers are initialized and this means that the application is completely
loaded. So this function is a good place to instantiate our main view. For now, we will only add
console.log
, which just prints on the browser's JavaScript interpreter console to v
erify if the
application was loaded successfully.


To execute this application on the browser, we can access
http://localhost/result
, and we will
get the

following output

in console press(CTRL + SHIFT + I ) in chrome or (CTRL+SHIFT + K)
in firefox
:



When

working with large Ext JS applications, it is normal to have a small delay when loading
the application. This happens because Ext JS is loading all the required classes to have the





Create Application using Ext Js

|

5



application up and running and meanwhile, all the users see is a blank scr
een, which can be
annoying for them. A very common solution to this problem is to have a loading page, also
known as a splash screen.

So let's add a splash screen to our application that looks like the following:





First we need to understand how this s
plash screen will work. At the moment the user loads the
application and the loading screen will be displayed. The application will show the splash screen
while it loads all the required classes and code so the application can be used.


We already know tha
t the application calls the launch function when it is ready to be used. So we
know that we will need to remove the splash screen from the launch method. The question now
is where inside
Ext.application

can we call the splash screen? The answer is inside t
he
init
function. The
init
function is called when the application boots so it gives some time for all
required code to be loaded and after that the launch function is called.

Now that we know how the splash screen will work, let's implement it.

Inside
Ext
.application
, we will implement a function called
init
:

result/app.js

Ext.application({


name: 'MyApp',







Create Application using Ext Js

|

6



init: function() {


splashscreen = Ext.getBody().mask('Loading Please Wait', 'splashscreen');

},

launch: function() {


console.log('lau
nch');


}

});



All we need to do is apply a mask into the HTML body of the application (
Ext.getBody()
), and
that is why we are calling the
mask

method passing the loading message ("Loading Please
Wait") and applying a CSS, which will be loading gif
and is already part of the Ext JS CSS
("splashscreen"). The mask method will return
Ext.dom.Element
, which we will need to
manipulate later (remove the mask from the HTML body) and for this reason, we need to keep a
reference to
Ext.dom.Element

and we will

store this reference inside an attribute of
Ext.application
:


result/app.js


Ext.application({


name: 'MyApp',


splashscreen: {},


init : function()

{











}
,


..



});



With the code of the
init

method only, we will have a loading screen as
the following:









Create Application using Ext Js

|

7



If this is all you need that is ok. But let's go a little bit further and customize the loading screen
adding a logo image so it can look like the first image of this topic, which is our final output.

First, we need to create a CSS file
which will contain all the CSS for our application. First create
css

folder inside
result/
resources/
and then create
css

file

We will name it as
app.css

and put it
inside a
result/
resources/css
/
folder:


Inside
resources

we will also create an
images

folde
r with the Attuneuniversity logo image.

We also must not forget to add the new CSS file into
result/
index.html
:


<link rel="stylesheet" href="resources/css/app.css">



Now add following things to

result/resources/css/
app.css

file we just created


.x
-
mask.s
plashscreen {


background
-
color: #efefef;


opacity: 1;

}

.x
-
mask
-
msg.splashscreen,

.x
-
mask
-
msg.splashscreen div {


font
-
size: 16px;


font
-
weight: bold;




padding
-
top : 17px;


padding
-
right : 40px;






border: none;


back
ground
-
color: transparent;


background
-
position: top center;

}


.x
-
message
-
box .x
-
window
-
body .x
-
box
-
inner {


min
-
height: 93px !important;

}


.x
-
splash
-
icon {


background
-
image: url('../images/logo.png') !important;


background
-
repeat :

no
-
repeat;




margin
-
top:
-
30px;


margin
-
bottom: 15px;


height: 100px;


width : 200px;



}


We will be adding a new CSS style to the loading
DIV

tag. Note that the following styles from
our
app.css
file will be applied
:
.x
-
mask.splashscreen

and
.x
-
mask
-
msg.splashscreendiv
. This





Create Application using Ext Js

|

8



will going to change the font of the "Loading Please Wait" message.


Now we will add the following code in the

init

function inside
result/app.js
:


init: function() {



splashscreen = Ext.getBody().mask('Loading
Please Wait' , 'splashscreen');


splashscreen.addCls('splashscreen');


Ext.DomHelper.insertFirst(Ext.query('.x
-
mask
-
msg')[0], {



cls: 'x
-
splash
-
icon'


});



},



After we execute the previous code, we will have an output exactly as the image we sh
owed at
the beginning of this topic.


Now we already have the splash screen being displayed. We need to work on the launch function
to remove the splash screen after all the code the application needs is loaded, otherwise the
loading message will be there
indefinitely!


To remove the splash screen the only code we need to add to the

launch

function is the following
one, which is removing the mask from the HTML body:

result/app.js

Ext.getBody().unmask();


However, removing the mask abruptly is not nice becau
se the user cannot even see the loading
message. Instead of only removing the mask, let's give the user 2 seconds to see the loading
message after the application is ready:

result/app.js

var task = new Ext.util.DelayedTask(function() {


Ext.getBody().
unmask();

});


task.delay(2000);


To do so, we are going to use the
DelayedTask

class, which is a class that provides a chance of a
function to be executed after the given timeout in milliseconds. So in the case of the task, we are
removing the mask from

the HTML body after two seconds of timeout (2,000 milliseconds).






Create Application using Ext Js

|

9



If we test the output right now, it works, but it is still not nice for the user. It would be even better
if we can add an animation to the masking. So we will add a fade out animation (whic
h animates
the opacity of an element from opaque to transparent) and after the animation we will remove the
masking (inside the
Ext.util.DelayedTask

function).


result/app.js

splashscreen.fadeOut({


duration: 1000,


remove:true

});


After we execute
this code, notice that the loading message is still being displayed.Only the first
DIV

tag with the class
splashscreen

was faded out. We need to also fade out the
DIV

tag with
class
x
-
mask
-
msg

splashscreen

that contains the logo and the loading message.


r
esult/app.js

splashscreen.next().fadeOut({


duration: 1000,


remove:true

});


After the loading mask is removed, we need to display the initial component of our application.
We will be showing a
main

screen that we will implement in the next. For now
, we will add a
console message just to know where we need to call the initial component
.
The complete code
for the launch function will be the following

:

result/app.js


launch: function() {


console.log('launch');



var task = new Ext.util.Del
ayedTask(function() {




splashscreen.fadeOut({


duration: 1000,


remove:true


});



splashscreen.next().fadeOut({


duration: 1000,






Create Application using Ext Js

|

10




remove:true,




listeners: {


afteranimate: function(e
l, startTime, eOpts ){


// Here we put the code to display Our Main Screen


}}


});


Ext.getBody().unmask();

});


task.delay(2000);



}

});



4.

Creating Main Screen

Now we are going to design our main screen but before that le
t’s understand
structure how

we
create our main screen

We are going to divide main screen in four parts

I.

Header

II.

Grid Panel which display student records

III.

Chart Which Display Result

IV.

Footer

The Structure of our main screen is as below:
















Create Application using Ext Js

|

11




Header



Stu
dent Grid

Toolbar For Student Grid



Grid Comes here








Chart

Toolbar for Chart


Chart comes Here











Footer









Create Application using Ext Js

|

12



This is how we create main page of our application we are dividing in to four parts Header,
Student Grid, Chart and last Foot
er


Now let’s create a view port for that
Create a file called
MyViewport.js
in

result/app/view/

folder

result/app/view/MyViewport.js

Ext.define('MyApp.view.MyViewport', {


extend: 'Ext.container.Viewport',


alias: 'widget.myviewport',


layo
ut: {


type: 'vbox' ,


align : 'stretch'


},


items: [


{


xtype: 'container',



layout : 'fit',


height: 50,


style: 'border
-
bottom: 4px solid #4c72a4;background
-
color : #B0C4DE',




h
tml: '<div id="titleHeader">Result<span style="font
-
size:12px;">
-

Student Result
Available Here</span></div>'



},


{


xtype: 'container', //Grid Panel Comes Here


flex : 1,



layout : 'fit',



style: '
background
-
color: #dedede;'


},



{


xtype: 'container',//Chart Panel Comes Here



flex : 2,



autoScroll : true,


},






Create Application using Ext Js

|

13




{


xtype: 'container',



layout : 'fit',



height: 30,


style: 'border
-
top: 1px solid #4c72a4;background
-
color : #B0C4DE',


html: '<div id="titleHeader"><center><span style="font
-
size:10px;">Demo of Student
Result</span></center></div>'


}


]

});

And we get fo
llowing output:





Now Let’s Understand How can we create a main screen:





Ext.define is used to create a class
in Ext Js




We have create a class MyApp.view.MyViewport now in that we created a namespace
MyApp now we have a view folder inside result/app/v
iew and in that view folder we created
a class called
MyViewport.js

so we have the same class name
MyViewport

which is a
specialized container representing the viewable application area (the browser viewport). The
Viewport renders itself to the document bo
dy, and automatically sizes itself to the size of the
browser viewport and manages window resizing.






Create Application using Ext Js

|

14





extend
:
'Ext.container.Viewport'

it means we are extending(inherit) it from
Ext.container.Viewport class this is Viewport.js file available in ext js libera
ry
result/ext/source/container/Container.js and we are define a container




alias: 'widget.myviewport'
,

this is we created an alias for our class
‘MyApp.view.MyViewport’
so we can use alias for the class so we can use it using alias
name myviewport




Afte
r that we create an
layout

properties here we use
vbox

layout

it means all the
components are arranged in the vertical format and also we are using stretched align so each
component will take all space vertically




Then, we add items one by one



Xtype : ‘co
ntainer’
, it will create a container this is another way how we can create a
container



we create here four container as four items




we also specify height, style parameters and html parameters in items


5.

Creating a grid for student details


Grid is used to

display the data.


First
Question

come in to your mind is how will grid display data?

Answer is:

1.

In Ext Js to Display Data First we have to create a
model

that defines the structure of
grid. in model we define What are the data grid contain and what type
of the data.

2.

Then we create a
store
, A store will fetch the data from server in json/xml format.

3.

Then we create a
gridpanel

(
View
)
which finally shows a data.

4.

And last we create a
controller

to handle the events and functionality in the gridpanel

So Ext
Js this way follows
MVCS

Model,
View,

Controller

and
Store

architecture

5.1

Crating A Modal For Grid

We are going to create a grid which will display Result of the Student i.e. Name, Age, Email
-
id
and
Stander
and subject name and marks for that we will creat
e a model

In
result/app/model

folder we will create a file called
Student.JS

which will display the student
data






Create Application using Ext Js

|

15



result/app/model/Student.js

Ext.define('MyApp.model.Student', {


extend: 'Ext.data.Model',



fields: [


{



name : 'id'


},


{



name: 'name'


},


{


name: 'age'


},


{


name: 'email'


},


{


name: 'sem'


},


{


name: 'photo'


},


{


name: 'Result'



}


]

});


We create a student model
which is extend from Ext.data.Model. This model is having

fields
required
are

id (student id), name, age, email, sem, photo and result details

5.2

Creating Store for Grid

Now we will create a store which will fetch

all student data in json format

for that we create a
file called
Students.js

in

result/
app/store

folder








Create Application using Ext Js

|

16



result/app/store/Students.js

Ext.define('MyApp.store.Students', {


extend: 'Ext.data.Store',



requires: [


'MyApp.model.Student'


]
,



model: 'MyApp.model.Student',


autoLoad : true,




proxy: {


type: 'ajax',


url: 'php/studentlist.php',




reader: {


type: 'json',


root: 'data'


}


}

});



We created a store which
is extend from Ext.data.Store.

We require a model to load the data because store load the data according to model

We also provide autoload facility here so store is automatically loaded

Ext Js is client script and data store on database so to access the da
ta we are using proxy. Type of
the proxy is ajax because we are making an ajax request for user interaction

We are fetching data from php file called studentlist.php which will send data in json format with
root is data


These are the two php file we are u
sing to fetch the data








Create Application using Ext Js

|

17



I.
db.php created in
result/php/db/

folder

result/php/db/db.php

<?php

$server = "127.0.0.1";

$user = "root";

$pass = "";

$dbName = "student";


$mysqli = new mysqli($server, $user, $pass, $dbName);


/* check connection */

if ($mysqli
-
>connect_errno) {


printf("Connect failed: %s
\
n", mysqli_connect_error());


exit();

}

else

{}

?>

II.

studentlist.php created in
result/php/
folder

result/php/studentlist.php

<?php


require("db/db.php");

$folder = array();


$sql = "SELECT * FROM stude
nt_master";


if ($resultdb = $mysqli
-
>query($sql))


{


while($r = $resultdb
-
>fetch_assoc())


{




$sqlquery = "SELECT sub,marks FROM student_result WHERE student_id = $r[id]";


if ($nodes = $mysqli
-
>query($sqlque
ry))



{




$count = $nodes
-
>num_rows;




if ($count > 0)





{






Create Application using Ext Js

|

18







$r['Result'] = array();





while ($item = $nodes
-
>fetch_assoc())






{





$r['Result'][] = $i
tem;




}





}










$folder[] = $r;



}


}


}


$resultdb
-
>close();

$mysqli
-
>close();


echo json_encode(array("data" => $fo
lder));

//
json format data

?>


So we created a php files which will give the data in json format
like

this

{"data":[{"id":"1","name":"Raj
Patel","age":"17","email":"student1@demosite.com","sem":"1","photo":"1.jpg","Result":[{"sub":"
Maths","marks":"85"},{"s
ub":"Science","marks":"80"},{"sub":"English","marks":"72"}]},{"id":"2
","name":"Vishal
Joshi","age":"17","email":"student2@demosite.com","sem":"1","photo":"2.jpg","Result":[{"sub":"
Maths","marks":"25"},{"sub":"Science","marks":"65"},{"sub":"English","marks"
:"78"}]},{"id":"3
","name":"Riyaz
Khan","age":"17","email":"student3@demosite.com","sem":"1","photo":"1.jpg","Result":[{"sub":"
Maths","marks":"46"},{"sub":"Science","marks":"52"},{"sub":"English","marks":"88"}]},{"id":"4
","name":"Sonali
Sharma","age":"17","
email":"student4@demosite.com","sem":"1","photo":"4.jpg","Result":[{"sub
":"Maths","marks":"88"},{"sub":"Science","marks":"26"},{"sub":"English","marks":"56"}]},{"id"
:"5","name":"Pankaj
Shah","age":"17","email":"student5@demosite.com","sem":"1","photo":"5.j
pg","Result":[{"sub":"
Maths","marks":"90"},{"sub":"Science","marks":"89"},{"sub":"English","marks":"56"}]}]}






Create Application using Ext Js

|

19



5.3

Creating a Grid Panel

(View of the Grid)

N
ow we will create a grid panel in Ext Js for that first create file called
Student
List
.js
.


result/app/vi
ew/Student
Li
s
t
.js

Ext.define('MyApp.view.StudentList', {


extend: 'Ext.grid.Panel',


alias: 'widget.studentlist',


frame: false,


store: 'Students'


columns: [


{


width: 150,


dataIndex: 'name',


text
: 'Name',



flex : 2



},


{


width: 100,


dataIndex: 'age',


text: 'Age'


},



{


width: 250,


dataIndex: 'email',


text: 'Email id'


},


{


width: 250,


dataIndex: 'sem',


text: 'Semister',



},


{flex: 1,



dataIndex: 'photo',



itemId: 'photoimage',



text: 'Profile Photo',



renderer : function(val)



{



return '<img src=" reso
urces/images/profilephoto/' + val + ' " width ="50" height="50">';




}







Create Application using Ext Js

|

20







},



]

});




We create a grid panel Extend it from
Ext.grid.Panel



Giving
alias

name

to studentlist and
frame

property to false



Then we assign store Students i.e.
MyApp.store.
Students

which will fetch the student data



Then we create a columns i.e name, age, sem, email and photo
in columns dataIndex value
must match the field we created in model and fields which are return by php in json format



In photo filed we created a funct
ion so when this column is renderd it will give an
image(profile photo) so we can see a profile photo in the grid


5.4

Creating a controller

for
Gird Panel

Now we create a controller for grid panel as
for that we create a file called

Students.js


result/app/co
ntroller/Students.js
:

Ext.define('MyApp.controller.Students', {


extend: 'Ext.app.Controller',



views: [


'Student
List
',



],



refs: [



{


ref: 'studentList',


selector: 'studentlist'


},






],

stores
: [


'Students',



],


init: function(application) {






Create Application using Ext Js

|

21




this.control({


"studentlist": {


render: this.onRender,




},






});



if (!Ext.getStore('Students')) {



console.log ("store
created");


Ext.create('MyApp.store.Students');


}


},



onRender: func
tion(component, options) {


component.
getStore().load();


},



});




We create a controller for the grid

which is extend from the
Ext.app.Cont
roller



In this flie we create a all functionality and handles all events



Then we have the

views

declaration, which is where we are going to declare all the views that
this controller will care about.



we will create a
reference

for the studenlist component
, where xtype is studentlist and we will
name ref as
studentList
. With this ref declared, the controller will
automatically generate

the
getStudentList()

method for us to retrieve the reference of this component.



Next, we h
ave the init method declaration.
The init method is called before the application
boots, before the launch function of Ext.application (app.js). The controller will also load the
views, models, and stores declared inside its class.



Then we have the control method configured. This is where

we are going to listen to all events
we w
ant the controller to react.



Then we listen a event of render of Grid Panel
stdentlist

by creating function
onRender

when
a grid panel “
Studentlist
” is render this function will call



In that function we load the st
ore of the grid so in grid we can see the data







Create Application using Ext Js

|

22



5.5

Make Changes in MyViewport.js


Open
result/app/view/MyViewport.js

and make following changes


Ext.define('MyApp.view.MyViewport', {


extend: 'Ext.container.Viewport',


alias: 'widget.myviewport',


requires: [




'MyApp.view.Students'


],

..

..

items:

[







{


xtype: 'students'
, //
Grid Panel Comes Here


flex : 1,



layout : 'fit',



style: 'background
-
color: #dedede;'


},







]

});




Change
the xtype to studentlist
where

we give comment

gridpanels come here


for that we
have to add requires property in MyViewport.js file

because we want to use this class



5.6

Make Changes
in
to the app.js


Finally we have to make following changes to our
result/
app.js

file



Ext.application({


name: 'MyApp',


splashscreen: {},



requires: [




'Ext.data.proxy.Ajax',



'MyApp.view.MyViewport'


],


controllers :[






Create Application using Ext Js

|

23






'Students',




],

init : function(){













}










});


We have to put Ext.data.Ajax in requires
otherwise

it will give warning and we must not fotgot
to put controller we just created i.e.


So after all this changes we get following output:






6.

Creating a Chart for Student Result




st
udent result we are showing in chart

for better view.



So when user click on grid panel item student result will see in the chart below

of the grid
panel



So Again for chart we will design a model, store, view and controller.



6.1

Creating a model for chart






Create Application using Ext Js

|

24




F
irst we create a model for chart we will display subject and marks in charts so in mod
e
l we
define subject and marks


So create a file called StudentChart.js in
result/app/model

folder.


result/app/model/StudentChart.js

Ext.define('MyApp.model.StudentChart
', {


extend: 'Ext.data.Model',



fields: [


{


name: 'sub'


},


{


name: 'marks'


}


]

});


We create a model for chart with fields sub and marks


6.2

Creating a store for
Chart


After creating a mode
l next step is create a store so create a file called
StudentChartStore.js

in
result/app/store/ folder


result/app/store/StudentChartStore.js

Ext.define('MyApp.store.StudentChartStore', {


extend: 'Ext.data.Store',



requires: [


'MyApp.model.
StudentChart'


],



constructor: function(cfg) {


var me = this;


cfg = cfg || {};


me.callParent([Ext.apply({


model: 'MyApp.model.StudentChart',


proxy: {


type: 'ajax',


read
er: {


type: 'json'


}


}






Create Application using Ext Js

|

25




}, cfg)]);


}

});


So we create a store for chart here we don’t give any php file because we are going to use the
data fetch from stdentlist.php



6.3

Creating a chart (View of
Chart)


Here we are create a charts to view the result
for that we will create a column chart

Create a file called
ColumnChart.js

in
result/app/view

folder

Ext.define('MyApp.view.ColumnChart', {


extend: 'Ext.chart.Chart',


alias: 'widget.columnchart
',


animate: true,


store: 'StudentChartStore',


shadow: true,


insetPadding: 60,


theme: 'Base:gradients',


axes: [{


type: 'Numeric',


position: 'left',


fields: ['marks'],


label: {


rendere
r: Ext.util.Format.numberRenderer('0')


},


title: 'Marks',


grid: true,


minimum: 0,


maximum: 100,



}, {


type: 'Category',


position: 'bottom',


fields: ['sub'],


title: 'Subject'


}],



series: [{


type: 'column',


axis: 'left',


highlight: true,


tips: {


trackMouse: true,


width: 140,


height: 28,






Create Application using Ext Js

|

26




renderer: function(storeItem, item) {


if(storeItem.get('marks'
) >= 40)



{



this.setTitle(storeItem.get('sub') + ': ' + storeItem.get('marks') + ': Pass');



}



else



{




this.setTitle(storeItem.get('sub') + ': ' + storeItem.get('marks') + ': Failed');



}


}


},


label: {



display: 'insideEnd',


'text
-
anchor': 'middle',


field: 'marks',


renderer: Ext.util.Format.numberRenderer('0'),


orientation: 'vertical',


color: '#333'


},


xField: 'sub',


yField: 'marks'


}]

});





Here we create a column chart which is extend from
Ext.chart.Chart
.



We assign
alias name

which is
columnchart

and set animate property to true



Then we assign a
store

for chart i.e.
StudentChartStore




After That we are define
Axe
s

of chart
i.e.

marks

and
subject



We are giving type of
mark

ax
e
s

to
numeric

and
position

to

left

means marks are displayed
at left side of axe
s



We assign marks in
field

property so name “
marks
” is same as “
marks
” we got in json and
declare in model Studen
tChart



We define
maximum

and
minimum

property for marks because marks



Similarly we define axes for subject and give its
type

to
category




After axes we define that
series

of chart is
column
.



We are assigning
highlight

to
true

it means when you hover the mo
use on column of chart it
is get highlighted



Tips are the message we wanted to display here we wanted to show a message when you
hover mouse on column message will be displayed
whether a student

is passed or failed with
marks




Then we are going to display

the mark inside column so we put label properties




And finally we will show
subject

on
x
-
axes

and
marks

on
Y
-
axes






Create Application using Ext Js

|

27







6.4

Adding Functionalities to grid controller


Whenever user selects any student record from the grid panel, we will show result of that stu
dent
in chart


So we have to add our logic
when grid

panel is selected

so open the
result/app/controller/Students.js and in that we are going to make following changes


Ext.define('MyApp.controller.Students', {


extend: 'Ext.app.Controller',



views
: [ 'Students' ],


requires :


['MyApp.view.MyViewport',


'MyApp.view.ColumnChart',


'MyApp.util.Alert'


],



refs: [


{ ref: 'studentList',


selector: 'studentlist'


},


{ ref: 'ColumnChart',



selector: 'columnchart'


},


],

stores: [


'Students',


'StudentChartStore'


],


init: function(application) {



this.control({


"studentlist": {


render: this.onRender,



select : this.
onGridpanelSelect





}





});



if (!Ext.getStore('Students')) {



Ext.create('MyApp.store.Students');


}






Create Application using Ext Js

|

28




},



onRender: function(component, options) {


component.getStore().load();


},

onGridpanel
Select: function(rowmodel, record, index, eOpts) {



var qualityData = record.get('Result');




var maths = qualityData[0]['marks'];



var science = qualityData[1]['marks'];




var English = qualityData[2]['marks'];



var per = parseInt(maths
) + parseInt(science) + parseInt(English);




per = parseFloat(per/3).toFixed(2);




if(maths < 40 || science < 40 || English <40)



{





var failsub = "";




if(maths < 40)




{failsub = "Maths";}




if(science < 40)




{failsub = failsub +" Science";
}




if(English < 40)




{failsub = failsub +" English";}




MyApp.util.Alert.msg("Bad Luck", record.get('name') + " Failed The Exam
with" + per + "% in " + failsub);




}



else



{

MyApp.util.Alert.msg("Congratulation", record.get('name') + " Passed The

Exam with" + per + "%");



}



var chart = this.getColumnChart();




chart.store.loadData(qualityData);







},


});



We make changes to the
controller first

we added
MyApp.view.ColumnChart

and

MyApp.util.Alert

in

require property because we will use t
his classes in our controller


We are make one class
Alert.js

and put it inside
result/app/util/

folder here we are not going to
show the code of that class it is used for display the message


Then we add
columnchart

in refs so we added reference of it and

getColumnChart()

method
automatically generated


I
nside this.control function we add fuction
onGridPanelSelect
on

select event of gridpanel







Create Application using Ext Js

|

29



In onGridPanelSelect function first we fetch the
result data

from the store of the grid in
qualityData

variable


F
rom that result data we fetch marks of
Maths
,
English
, and
Science

and we put the logic of
calculating percentage and display the message whether student is passed or not


Finally we get an instance of chart by getCoulmnChart() method and load the store of

the chart
by result data of grid store which contain marks and subject as json data. That’s why we can see
the chart of particular student selected in the grid


6.5

Make Changes in MyViewport.js


Open
result/app/view/MyViewport.js

and make following changes


Ext.define('MyApp.view.MyViewport', {


extend: 'Ext.container.Viewport',


alias: 'widget.myviewport',


requires: [




'MyApp.view.Students',


‘MyApp.view.ColumnChart’


],

..

..

items:

[







{


xtype: columnchart
, //
C
hart
Panel
Comes Here


flex : 1,



layout : 'fit',



style: 'background
-
color: #dedede;'


},







]

});




Change the xtype to
columnchart

where we give comment “
Chart Panel

C
ome
s

H
ere” for that
we have to add requires property

in MyViewport.js file because we want to use this class




6.6

Make Changes in result/app.js







Create Application using Ext Js

|

30



Ext.application({


name: 'MyApp',


enableQuickTips : true,




splashscreen: {},



views : [





'Main',





'Viewport',




'MyViewport'




],


requires: [





'MyApp.view.MyViewport',





'Ext.data.proxy.Ajax',





'MyApp.util.Util',






'Ext.layout.container.Card',






'Ext.chart.series.Pie',





'Ext.chart.series.Column',





'Ext.chart.axis.Numeric',





'Ext.chart.a
xis.Category',






'MyApp.view.PieChart',






'MyApp.view.ColumnChart'




],

controllers :[






'Students',





],





init : function()

{










}









});





We added required components in required properties



So Now when user c
lick on any student data from the grid panel

the result of the student is
displayed in chart and message is displayed whether student is passed or failed in exam



When you hover a mouse on column of a chart the marks of the particular subject is
displayed w
ith student is passed or failed in that subject



Now let’s see the output:







Create Application using Ext Js

|

31