Sunday, December 9, 2012
ExtJS 4–Data Framework–Models-Association–Part 3
The models can be associated to create complex data model. Both single values and multi valued association can be defined in Ext Data framework. The association are defined using “associations” configuration in model.
Lets take for example we have Person and Address model. The association is that Person has multiple address (Shipping, billing etc.).
The code snippet below describes the two model as discrete class. we will had association in next snippet.
Ext.define('Training.model.Person', {
extend:'Ext.data.Model',
fields:[
{
name:'firstname',
type:'string'
},
{
name:'lastname',
type:'string'
},
{
name:'dob',
type:'date',
dateFormat:'m-d-Y'
},
{
name:'single',
type:'boolean'
},
{
name:'gender',
type:'string'
}
]
});
Ext.define('Training.model.Address', {
extend:'Ext.data.Model',
fields:[{
name:'street',
type:'string'
},{
name:'city',
type:'string'
}]
});
ExtJS 4–Data Framework–Models-Validation–Part 2
Continuing from previous post. Lets add some validation to the model. Data validation can be specified in models through the validations configuration array. Validation available are
| presence | Field has to have a value. Empty strings are not valid. Zero (0) is valid |
| length | can be b/w min and max length |
| inclusion | set of values |
| exclusion | not in a set of values |
| format | regular expression format. For example : email format |
Validating Data
We need to call validate() method on the model object to validate. The model object returns a Ext.data.Errors Object. Method in Ext.data.Errors of use are
| isValid() | true if there are not errors |
| forField(fieldname) | Error objec for the field |
| each(function) | iterate over the error object and display the errors |
Let’s see how to validate and get error object next.
Ext.define('Training.model.Person', {
extend:'Ext.data.Model',
fields:[
{
name:'firstname',
type:'string'
},
{
name:'lastname',
type:'string'
},
{
name:'dob',
type:'date',
dateFormat:'m-d-Y'
},
{
name:'single',
type:'boolean'
},
{
name:'gender',
type:'string'
}
],
validations:[
{
type:'presence',
field:'firstname'
},
{
type:'inclusion',
field:'gender',
list:['M', 'F']
}
]
});
var init = function () {
var newPerson = Ext.create('Training.model.Person', {
lastname:'Doe',
dob:'10-21-2001',
single:true,
gender:'do-not-bother'
});
// call the validate() method to check if the model has correct values
var errors = newPerson.validate();
console.log("Errors is "+ errors);
if(!errors.isValid()){
errors.each(function(error){
console.log("Field : "+ error.field+" message : "+ error.message);
})
}
};
Ext.onReady(init);
As we see in above code, we have defined two validation, one for firstname as presence validation and another for gender as inclusion. The inclusion list is specified in array. We are creating a newPerson object in the init function. Wee are not setting value for “firstname” and for gender we are setting some arbitrary value. The validations fail on call to validate(). The errors object is iterated to display individual error. The console displays the following error.
The demo can be found here
ExtJS 4–Data Framework–Models–Part 1
In this post, we will be defining a Model and then we will define model and then validations on that. The class to extend is “Ext.data.Model”.
Ext.define('Training.model.Person', {
extend:'Ext.data.Model',
fields:[
{
name:'firstname',
type:'string'
},
{
name:'lastname',
type:'string'
},
{
name:'dob',
type:'date',
dateFormat:'m-d-Y'
},
{
name:'single',
type:'boolean'
}
]
});
The above model defines 4 fields. As we can see we can define a field of type date. The dateFormat defines the input format which will be parsed when we set the value for firstname. We can create object using Ext.create('Training.model.Person') and supply a config object as shown below. To access individual properties, we use Ext.get('fieldname').
var newPerson = Ext.create('Training.model.Person',{
firstname:'John',
lastname:'Doe',
dob:'10-21-2001',
single:true
}) ;
console.log("First name: "+newPerson.get('firstname'));
console.log("Last name: "+newPerson.get('lastname'));
console.log("dob: "+newPerson.get('dob'));
console.log("single: "+newPerson.get('single'));
The demo can be found here
ExtJS 4–Data Framework
The three mail components in Data framework are
- Model
- Store
- Proxy
The model class is the new and most important class in Ext.data package. It is the improvement over Record class in Ext 3.x. Now, we can represent real entities using Model classes. Now, proxy can be attached to model class so that they can talk to server to load, update, delete and create models.
The model class following features
- Fields
- functions
- Validations
- Associations.
Saturday, December 8, 2012
Ext JS 4–DOM Handling
ExtJS has core framework which helps in dom handling and event management.
The main class is Element class which is ExtJS wrapper around the dom nodes. There are ExtJS utilities to select and manipulate the Dom elements.
The Element class normalizes the DOM manipulation and provides positioning capabilities.
There are two way to get the Element
- Ext.get(id)
- Ext.fly(id).
Both method takes the id of element we are referring in the page. Lets see a example
In the example above, we are trying to get the value of three text box defined. We are using Ext.get(‘fname’) to get the Element wrapper for fname textbox. We can add animation to using element.highlight() or frame(). All Element object have animation method added to it as Mixins. Let see the enhanced code, On click of button lets highlight the textboxes.
ExtJS - Demos
This is a h2 header
Person Form
fnameEl.highlight("0000ff", {
duration : 2000
});
lnameEl.highlight("0000ff", {
duration : 2000
});
cityEl.highlight("0000ff", {
duration:2000
});
The demo can be found here
ExtJS 4–Classes–Dynamic Loading
In previous posts, we have been looking at defining classes and statics. The process was to define a class in the JavaScript file and access it. So we include individual JavaScript file (which define the class) to the page. But in dynamic class loading, the ExtJS Loader (Ext.Loader) does a dynamic resolution of classes based on the configured folder structure. The process is two part
- Define the classes in respective js file location in correct folder structure
- Enabling dynamic loading and setting the path resolution. For example,
// Configure the loader
Ext.Loader.setConfig({
enabled:true,
paths:{
package1:'path to package1',
package2:'path to package2'
}
});
The code above enables the dynamic loading and set the package resolution. Let take the Person class define in previous post
Step 1
The process is to move the Person class to “person.js” located in following folder structure “training/classes/person.js” as shown below.
In my case, I am placing person.js in “js/applicaiton/training/classes” folder. The code of “person.js” is given below.
// Define a person class
Ext.define('Training.class.Person', {
// list of properties, setter and getter of all the property will
// be available on instantiation.
config:{
firstname:'',
lastname:'',
age:'',
city:'',
country:''
},
constructor:function (config) {
this.initConfig(config);
},
applyFirstname:function (value) {
return value.toUpperCase();
},
getLongName:function () {
return this.firstname + "," + this.lastname;
},
statics:{
count:'',
getCount:function () {
return this.count;
},
increment:function () {
this.count++;
}
},
// refer the static property by this.statics().count
getOuterCount:function () {
return this.statics().count;
}
});
The code is just the copy from previous post.
Step 2
The next step is to configure the loader so that when we create object for Person class it is able to resolve the class. So, we need to configure “Training” package to “js/application/training” folder. The code is as defined below.
Ext.Loader.setConfig({
enabled:true,
paths:{
'Training':'js/application/training'
}
});
Now we need not include person.js in the page where we create person object. The loader will resolve the class to load.
The page code is given below.
var init = function () {
// Configure the loader
Ext.Loader.setConfig({
enabled:true,
paths:{
'Training':'js/application/training'
}
});
var newPerson = Ext.create('Training.class.Person',{
firstname:'John',
lastname:'Doe'
});
console.log("First name is "+newPerson.getFirstname());
};
Ext.onReady(init);
We have only this code in page. When we instantiate using Ext.create(‘Training.class.Person’), the loader will dynamically load the Person.js as shown below.
As we see the loaded does a load when the class is required.
The demo can be found here
ExtJS 4 – Classes
ExtJS 4 provides a new class system with following capabilities
- Support for mixins
- Statics – propeties and methods
- Dynamic generation of getters and setters for class properties
- Automatic dependency management.
Defining a new class
Define a new class using “Ext.define()” method. Ext.define does the following
- creates the namespace
- can extend a exiting class
Lets define a class
// Define a person class
Ext.define('Training.class.Person', {
// list of properties, setter and getter of all the property will
// be available on instantiation.
config:{
firstname:'',
lastname:'',
age:'',
city:'',
country:''
},
constructor:function (config) {
this.initConfig(config);
}
});
As you can see from the above snippet, the class has set of properties and a constructor defined. The constructor takes a configuration object.
The call to “initConfig(…)” will create setter and getter.
We can create object by using Ext.create(…). The create method takes the class name (in this case ‘Training.class.Person’) and a JavaScript object (configuration). Lets see the code.
var init = function () {
// creating a object
var init = function () {
var newPerson = Ext.create('Training.class.Person', {
firstname:'John',
lastname:'Doe',
age:new Date(),
city:'Brooklyn',
country:'US'
});
// Use firebug to see the console output. if using IE use replace console.log with alert.
console.log('Person firsname '+newPerson.getFirstname());
console.log('Person lastname '+newPerson.getLastname());
console.log('Person age '+newPerson.getAge());
console.log('Person city '+newPerson.getCity());
};
};
Ext.onReady(init);
The demo can be found here
The automatic setters and getters are not to be overridden. Instead, the class framework provides ways to override them. For example, in Person class, we need to modify the firstname setter , we need to provide an applyFirstname function. The applyConfig function is invoked when we set the value.
Ext.define('Training.class.Person', {
// list of properties, setter and getter of all the property will
// be available on instantiation.
config:{
firstname:'',
lastname:'',
age:'',
city:'',
country:''
},
constructor:function (config) {
this.initConfig(config);
},
// called while setting value for setFirstname
applyFirstname:function(value){
return value.toUpperCase();
}
});
Similarly we can define applyLastname, applyAge….. .
The demo can be found here
We can define any number of custom function like code below.
Ext.define('Training.class.Person', {
// list of properties, setter and getter of all the property will
// be available on instantiation.
config:{
firstname:'',
lastname:'',
age:'',
city:'',
country:''
},
constructor:function (config) {
this.initConfig(config);
},
applyFirstname:function(value){
return value.toUpperCase();
},
// we can define method and call from the object.
getLongName:function(){
return this.firstname +","+this.lastname;
}
});
Saturday, August 11, 2012
ExtJS–Message Box
Ext.Msg is a singleton based on Ext.MessageBox class generating different types of message boxes.
There are four types of Message boxes
- alert
- Display a read-only message box with OK button (similar to javascript alert).The live example can found here
Ext.Msg.alert('Alert Box',
'This is a alert box.Html element
');
// To capture feedback
Ext.Msg.alert('Alert Box', 'This box will capture feedback.',
function(buttonId) {
Ext.Msg.alert('Feeback', "Button Clicked : " + buttonId);
});- confirm
Ext.Msg.confirm() displays a confirmation message box. It displays a message with Yes and No button. The code snippet is given below.The live example can be found here
Ext.Msg.confirm('Confirm Box', 'Do you wish to continue?', function(
buttonText) {
if (buttonText == "no") {
Ext.Msg.alert('No', "You clicked no");
}
if (buttonText == "yes") {
Ext.Msg.alert('Yes', "You clicked yes");
}
});- prompt
Prompt box can be used to get user input similar to javascript’s prompt. It has “ok” and “cancel”. The code snippet is given belowExt.Msg.prompt('Prompt', "Enter your name? ", function(btnTxt,The live example can be found here
inputText) {
if (btnTxt == 'ok') {
Ext.Msg.alert("Prompt ", "Your name is "+inputText)
}
});- Displaying a Custom Message Box
Ext.Msg.show() should be used display a custom message box. We can configure the title, msg, dimension, buttons, call back function, icon.
List of button types
- Ext.MessageBox.OK
- Ext.MessageBox.YES
- Ext.MessageBox.NO
- Ext.MessageBox.CANCEL
Icon can be
- Ext.MessageBox.INFO
- Ext.MessageBox.WARNING
- Ext.MessageBox.QUESTION
- Ext.MessageBox.ERROR
Ext.Msg.show({
title : 'Show Message Box',
msg : 'Please enter your address',
width : 300,
buttons : Ext.Msg.OKCANCEL,
multiline : true,
icon : Ext.window.MessageBox.INFO
});
The live example can be found here
Saturday, December 17, 2011
ExtJS 4– Adding Library and Testing
Download the ExtJS 4 from here.
Unzip to a folder. The file/folder required are as shown in the screenshot below.
Copy “ext-all-debug-w-comments.js” and resources folder to the web-application being developed.
My examples are based on grails framework. Details are available here
The folder structure for a typical grails integration will be
Adding library to the page in <head> section (html, jsp or gsp).
To test whether the extjs has be included in page. Add the following code below the above code.
The ExtJS onReady is fired once the page DOM is loaded in browser. Please refer ExtJS documentation for further insight.
All in all the head section of the page should look like this
Ignore the <meta….>, this is specific to grails.