Doing it with Forms

Exclusive offer: get 50% off this eBook here
Learning Ext JS 4

Learning Ext JS 4 — Save 50%

Sencha Ext JS for a beginner book and ebook.

£18.99    £9.50
by Armando Gonzalez Crysfel Villa | March 2013 | Open Source Web Development

Ext JS comes with powerful widgets to collect and edit data; we have the form component and many types of input widgets. These include textfields, textarea, radios, checkbox, combos, sliders, and many more.

In this article Crysfel Villa and Armando Gonzalez, authors of Learning Ext JS 4 , we are going to learn about the components we can use to collect data from our users. Also we are going to be working on our final application as well as creating the required forms in the wireframes.

We are going to cover the following topics in this article:

  • The form component

  • The available field types

  • Field container

  • Submitting the data

(For more resources related to this topic, see here.)

The form component

In order to collect and handle data Ext comes with the Ext.form.Panel class. This class extends from the panel so we can place the form in any other container. We also have all the functionality the panel offers, such as adding a title and using layouts.

If we look at the wireframes, we can see that we need to have the functionality of creating, editing, and deleting clients from our database:

We are going to work on this form. As seen in the previous screenshot the form contains a title, a toolbar with some buttons, and a few fields.

One important thing to keep in mind when working with Ext JS is that we should create our components isolated from the other components as much as we can. This way we can reuse them in other modules or even extend them to add new functionality.

First we need to extend from the Form class, so let's create a JavaScript file with the following code:

Ext.define('MyApp.view.clients.Form',{ extend : 'Ext.form.Panel', alias : 'widget.clientform', title : 'Client form', initComponent : function(){ var me = this; me.callParent(); } });

We need to create the file in the following path:

MyApp/view/clients/Form.js

The previous code doesn't do much, it's only extending from the form panel, defining an alias and a title. The initComponent method is empty, but we're going to create some components for it.

Now let's create an HTML file, where we can test our new class. We need to import the Ext JS library, our JS file, where our new class is, and wait for the DOM ready event to create an instance of our class:

<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Texfield</title> <!-- Importing the Ext JS library --> <script type="text/javascript" src = "../ext-4.1.1a-gpl/ext-all-dev. js"></script> <linkrel="stylesheet" href="../ext-4.1.1a-gpl/resources/css/ext-all. css" /> <script type="text/javascript" src = "MyApp/view/clients/Form.js"></ script> <script type="text/javascript"> Ext.onReady(function(){ Ext.create('MyApp.view.clients.Form',{ width : 300, height : 200, renderTo: Ext.getBody() }); }); </script> <style type="text/css"> body{padding:10px;} </style> </head> <body> </body> </html>

We are creating an instance of the Client form as usual. We have set the width, height, and the place where the form is going to be rendered, in this case the body of our document. As a result we have our form created as shown in the following screenshot:

So far we have an empty form. We can add any of the available components and widgets, let's start with the textfield property:

Ext.define('MyApp.view.clients.Form',{ extend : 'Ext.form.Panel', alias : 'widget.clientform', title : 'Client form', bodyPadding : 5, defaultType : 'textfield', //Step 1 initComponent : function(){ var me = this; me.items = me.buildItems(); //Step 2 me.callParent(); }, buildItems : function(){ //Step 3 return [{ fieldLabel : 'Name', name : 'name' },{ fieldLabel : 'Contact', name : 'contact' }]; } });

The steps are explained as follows:

  • Step 1: We have defined the default type of component we are going to use. This way we don't have to define the xtype property every time we want to create textfield.

  • Step 2: We use the items property to add components to our form. We are calling a function that should return an array of components.

  • Step 3: We are defining two textfields. First we set the value of the label for each textfield and then we set name. It's important to use name if we want to send or retrieve data to our server. Setting the name property will allow us to set and retrieve data to our fields in an easy way.

Using a function to define the items array is a great way to write our code for readability. Also if we would like to extend this class, we can override this method and add more components to our form in the subclass.

With the previous lines of code we have added two textfields to our form as shown in the following screenshot:

Now let's add the Address field to our form using a textarea property. In order to do that we need to override the default xtype property as follows:

Ext.define('MyApp.view.clients.Form',{ //... buildItems : function(){ return [ //... ,{ xtype : 'textarea', fieldLabel : 'Address', name : 'address' } ]; } });

If we want to define new components we can override the xtype property with the component we need. In this case we are using a textarea xtype, but we can use any of the available components.

The last field in our wireframe is a textfield to collect the phone number. We already defined the default xtype as textfield so we only need to define the name and the label of our new textfield as follows:

Ext.define('MyApp.view.clients.Form',{ //... buildItems : function(){ return [ //... ,{ fieldLabel : 'Phone', name : 'phone' } ]; } });

As a result we have all the required fields in our form. Now if we refresh our browser, we should see something like the following screenshot:

We have our form ready, but if we see our wireframe we can realize that something is missing. We need to add three buttons to the top of the panel.

We already know how to create toolbars and buttons; the following code should be familiar for us:

Ext.define('MyApp.view.clients.Form',{ //... initComponent : function(){ var me = this; me.items = me.buildItems(); me.dockedItems = me.buildToolbars(); //Step 1 me.callParent(); }, buildItems : function(){ //... }, buildToolbars : function(){ //Step 2 return [{ xtype : 'toolbar', docked : 'top', items : [{ text : 'New', iconCls : 'new-icon' },{ text : 'Save', iconCls : 'save-icon' },{ text : 'Delete', iconCls : 'delete-icon' }] }]; } });

In the previous code, we are defining the dockedItems property; we are using the same pattern of defining a function that returns the array of items in the first step.

In the second step we define a function that returns an array of components to be docked. In this case we are only returning a toolbar docked to the top; this toolbar contains three buttons. The first button is for a new client, the second one is to save the current client, and the third button is to delete the current client in the form.

We need to use CSS classes to add an icon to the buttons. The previous code is using three different classes so we need to create them:

<style type="text/css"> .new-icon{background:transparent url(images/page_add.png) 0 0 norepeat !important;} .save-icon{background:transparent url(images/disk.png) 0 0 no-repeat !important;} .delete-icon{background:transparent url(images/delete.png) 0 0 norepeat !important;} </style>

Once we have defined our CSS classes let's refresh our browser and see our latest changes in action:

We have finished our wireframe, but the form is not doing anything yet. For now let's just move forward and see what other components we have available.

Anatomy of the fields

Ext JS provides many components to give the user a great experience when using their applications. The following fields are components we can use in a form or outside of the form, for example, we can add a textfield or a combobox to a toolbar, where we place some filters or search options.

Every input field extends from the Ext.Component class; this means that every field has its own lifecycle, events, and also can be placed on any container.

There's also a class called Ext.form.field.Base that defines common properties, methods, and events across all form fields. This base class also extends from the Ext. form.Labelable and Ext.form.field.Field classes (using mixins).

The Labelable class gives the field the ability to display a label and errors in every subclass such as textfields, combos, and so on.

The Field class gives the fields the ability to manage their value, because it adds a few important methods, such as the getValue and setValue methods to set and retrieve the current value of the field; also this class introduces an important concept, the raw value.

A great example of the raw value is when we pull data from our server and we get a date value in string format, the raw value is in plain text, but the value of the date field should be in a native Date object so that we can work easily with dates and time. We can always use the raw value, but it's recommended to use the value instead, which in this example is a Date object.

Learning Ext JS 4 Sencha Ext JS for a beginner book and ebook.
Published: January 2013
eBook Price: £18.99
Book Price: £30.99
See more
Select your format and quantity:

Available fields

Ext JS provides many widgets that we can use to collect and edit data in our forms. We are going to learn about the most useful widget and configurations that we can use to create beautiful forms.

For the following examples we are going to create a class that extends from the Form class and hold the fields that we are going to explain in detail later on:

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', alias : 'widget.availablefields', title : 'Available fields', width : 280, bodyPadding : 5, initComponent : function(){ var me = this; me.items = me.buildItems(); me.callParent(); }, buildItems : function(){ //We are going to create the fields here return [] } });

In the buildItem form we are going to instantiate the required classes.

The Textfield class

We have already used this class to create our wireframe and we used the xtype property to create it. We can always create the instance using the Ext.create method and the class that we should instantiate is Ext.form.field.Text.

This class extends from the base class and is intended to manage text as a string value. This class defines some important events such as keydown, keypress, and keyup. These events are very useful to catch the keys the user is entering into a textfield.

It's important to keep in mind that if we want to use these events, we need to set the enableKeyEvents property as true.

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', //... buildItems : function(){ //Step 1 var txt = Ext.create('Ext.form.field.Text',{ fieldLabel : 'First name', name : 'firstname', enableKeyEvents : true }); //Step 2 txt.on('keyup',function(field,event,options){ if(event.getCharCode() === event.ENTER){ Ext.Msg.alert('Alert','Welcome: '+field.getValue()); } }); return [txt]; } });

In the first step we create a textfield component. We define some properties, such as the name and the label of the field and enable the key events.

In the second step we are setting a listener to the keyup event. Every time the user releases a key on his keyboard the callback function will be executed. In the previous example we are waiting for the Enter key and whenever it is pressed we show an alert message with the value entered into the textfield.

Ext JS provides a wrapper for the native event object. This wrapper defines many constants such as the Enter key. We can see all the available constants on the documentation at http://docs.sencha.com/ext-js/4-1/#!/api/ Ext.EventObject..

Let's test our code in a new HTML page as follows:

<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Texfield</title> <!-- Importing the Ext JS library --> <script type="text/javascript" src = "../extjs-4.1.1a-glp/ext-all-dev. js"></script> <linkrel="stylesheet" href="../extjs-4.1.1a-glp/resources/css/ext-all. css" /> <!-- Importing our custom class --> <script type="text/javascript" src = "MyApp/view/AvailableFields"></ script> <script type="text/javascript"> Ext.onReady(function(){ Ext.create('MyApp.view.AvailableFields',{ renderTo : Ext.getBody() }); }); </script> <style type="text/css"> body{padding:10px;} </style> </head> <body> </body> </html>

The following screenshot shows how our Textfield is working with the listener attached:

As we can see in the previous example all the fields extend from the Observable class, therefore we are able to add events and listeners to all form fields.

We should take a look at the documentation to see all the available events that we can use to our advantage.

The number field

When dealing with numbers we can use the number field that only accepts numbers as a value. This way we can assure that the user will not be able to introduce any invalid characters.

Let's add the following code to the buildItems method to see how the number field works:

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', //... buildItems : function(){ //... //Step 1 var num = Ext.create('Ext.form.field.Number',{ fieldLabel : 'Price', name : 'price' }); return [txt,num]; //Step 2 } });

In the first step we create the instance. We are only assigning the label and the name of our field. There are many more options, but for now we are only using these two.

In the second step the field is added to the returning array that will be added to the items of the form.

As a result we will have something as shown in the following screenshot:

As we can see in the previous screenshot the number field contains two arrows or spinners. If the user clicks on them, the value will increase or decrease accordingly.

By default the value is incremented or decremented by one, but we can control that by setting the step configuration as follows:

//... var num = Ext.create('Ext.form.field.Number',{ fieldLabel : 'Price', name : 'price', step : 10 }); //...

Now if we click on the spinners, we will see how they are increased by ten. Another useful configuration is to set the maximal or minimal value that this field will accept; we can achieve this by setting the minValue and maxValue configurations as follows:

//... var num = Ext.create('Ext.form.field.Number',{ fieldLabel : 'Price', name : 'price', step : 10, minValue : 30, maxValue: 100 }); //...

Finally, if we don't want to show the spinners, we can hide them by using the hideTrigger configuration as follows:

//... var num = Ext.create('Ext.form.field.Number',{ fieldLabel : 'Price', name : 'price', step : 10, minValue : 30, maxValue : 100, hideTrigger : true }); //...

This way the spinners will not be shown and we will have a textfield with the ability to accept only numbers.

There are many more configurations for this field, such as the ability to change the decimal separator so only numbers without decimals will be allowed and many more options that we can use to our advantage.

Even if we accept only numbers in our textfield, we should always run the validations in the server side, never rely only on the client side.

The combobox field

The combobox is one of the most useful widgets to display a list of options. This is a very flexible component that we can customize to our needs.

Let's start with the basics! First we need to rely on the data package that we have already learned earlier in this book. We are going to use the Store class with a local data to fill our combobox.

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', //... buildItems : function(){ //... //Step 1 var store = Ext.create('Ext.data.Store',{ fields : ['key','label'], data : [ {key:'xs',label:'Extra Small'}, {key:'s',label:'Small'}, {key:'m',label:'Medium'}, {key:'l',label:'Large'}, {key:'xl',label:'Extra Large'} ] }); //Step 2 varcombobox = Ext.create('Ext.form.ComboBox',{ fieldLabel : 'Size', name : 'size', store : store, queryMode : 'local', displayField: 'label', valueField : 'key' }); return [txt,num,combobox]; //Step 3 } });

In the first step we are creating a store with a static data. By defining the fields property the store internally creates the model to be used with this store.

In the second step we create our combobox. We are defining the name and the label as any other fields, but there are some specific configurations that are required for the combobox in order to work properly. First we set the store that the combobox will use to display the data. Then we need to set the queryMode property to local, by doing this the combobox will not try to load the data of the store remotely when the list of options is displayed. After that we need to define which of the properties in the store will be used for displaying the label in the list of options and which will be used as a value; we use the displayField and valueField properties to specify this.

The last step is to append our combobox to the returning array of fields that will be added to our form.

The following screenshot shows the result of our code:

Since we are using a store to hold the displayed data we can use an Ajax proxy to get the content of the store from our server.

Let's modify our previous example to get all the available sizes from our server side. First we need to create the service that will return the data; in this case we are going to use a static data, but this data can be stored in a database or somewhere else.

{ "success" : true, "data" : [ {"key":"xs","label":"Extra Small"}, {"key":"s","label":"Small"}, {"key":"m","label":"Medium"}, {"key":"l","label":"Large"}, {"key":"xl","label":"Extra Large"} ] }

The previous code should be located in a new file at serverside/size.json or anywhere else where you can make an Ajax request.

Once we have defined the source of data we need to perform some changes in our code as follows:

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', //... buildItems : function(){ //... var store = Ext.create('Ext.data.Store',{ fields : ['key','label'], autoLoad: true, proxy : { type : 'ajax', url : 'serverside/sizes.json', reader : { type : 'json', root : 'data' } } }); //... } });

As you can see we have changed the proxy of the store only. We defined an Ajax proxy and a JSON reader, now if we refresh our browser, we can see that the data is loading remotely.

This is one of the greatest advantages of Ext JS. We can change things very easily because Ext is built with small classes that can be switched at any time. We have seen how to read data locally and remotely.

At this point the user can type into the combobox and the list that will be displayed will contain only those records that matche with the current text entered. This is a very handy feature, but in most cases we want the user to select only one of the available options and not enter some invalid text. We can use the forceSelection property to force the user to select only one option even if he/she starts typing text into the field:

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', //... buildItems : function(){ //... varcombobox = Ext.create('Ext.form.ComboBox',{ fieldLabel : 'Size', name : 'size', store : store, queryMode : 'local', displayField: 'label', valueField : 'key', forceSelection : true }); return [txt,num,combobox]; } });

Now we can be sure that the user is going to select only one of the available options in the list:

It's very common that we need to do something when an option of the list is selected, for example load another combo or hide/show some other fields. We can listen to the select event and perform the required actions:

combobox.on('select',function(combo,records){ Ext.Msg.alert('Alert',records[0].get('label')); });

The previous code is listening to the select event, and only shows an alert message with the label of the record selected. Here we can do whatever we need, such as loading the data of another combobox depending on the selection of the first.

The callback receives the array of records selected; it's an array because we can also configure our combobox to allow the user to select more than one option.

We can use any of the available events to perform some actions but one of the most important events for this widget is the select event.

The date field

Ext provides an easy way to collect dates; we have at our disposal a date picker that will handle the selection of a date using a fancy calendar or by allowing the user to type the date in the format we define.

The most basic usage is by only setting the name and the label of the field such as the following code:

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', //... buildItems : function(){ //... vardatefield = Ext.create('Ext.form.field.Date',{ fieldLabel : 'Date', name : 'date' }); return [txt,num,combobox,datefield]; } });

We are defining our date field in a very simple way, but there are many more configurations we can use. Let's dig a little bit more to customize these fields to meet our requirements.

By default the format used to display the date is m/d/Y(05/22/2012) ; this is a common format used in the U.S., but not in other countries. To define a custom format for a different region or country we need to use the format property as follows:

vardatefield = Ext.create('Ext.form.field.Date',{ fieldLabel : 'Date', name : 'date', format : 'd/m/Y', submitFormat: 'Y-m-dH:m:s' });

We can use any format to display the date and also we can set the format that we want the field to be sent, when we submit the form, or retrieved, when we get the values. Defining the submitFormat property is very important because it's this format that we will be using under the hood; in this example we are using a common format in databases.

The m/d/Y format refers to the commonly mm/dd/yyyy format. This may be confusing, but we should take a look at the Ext.Date object documentation to see all the supported formats that we can use at http://docs.sencha.com/ ext-js/4-1/#!/api/Ext.Date.

Right now the user is able to type into the field to enter the date in the correct format, however using slashes may slow down the user. We can allow alternative formats to make things easier for the user, for example we could define d m Y as a valid format and as many formats as needed:

vardatefield = Ext.create('Ext.form.field.Date',{ fieldLabel : 'Date', name : 'date', format : 'd/m/Y', submitFormat: 'Y-m-d H:m:s', altFormats : 'd-m-Y|d m Y|d.m.Y' });

Using the altFormats property we can define all the formats we want. We only need to separate each format by a pipe character (|) and those formats will be used to parse the text to a date object. We should not use the pipe inside any of the format because there is no way to escape this character. A format like m|d|Y will not work.

We have many more properties available, such as minValue and maxValue, the ability to disable some specific dates such as weekends or holidays:

vardatefield = Ext.create('Ext.form.field.Date',{ fieldLabel : 'Date', name : 'date', format : 'd/m/Y', submitFormat: 'Y-m-d H:m:s', altFormats : 'd-m-Y|d m Y|d.m.Y', minValue : new Date(), disabledDates: ['30/04/2012','15/05/2012'] });

If we want to disable a range of days, we can use regular expressions to match the dates that we want to disable. Some examples are as follows:

//disable everyday in march 2012 disabledDates: ['../03/2012'] //disable everyday in march for every year disabledDates: ['../03/..'] //disable the 05 and 21 of march for every year disabledDates: ['05/03','21/03']

We can also use the select event that is fired when the user selects a date. We can do whatever we need inside the callback function as we did in the combobox.

The checkbox

We can use a single checkbox to set a record in our database as active or inactive, or maybe we can have a group of options that we need to display and allow the user to select a few of them:

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', //... buildItems : function(){ //... //Step 1 varchkbox = Ext.create('Ext.form.field.Checkbox',{ fieldLabel : ' ', labelSeparator : '', boxLabel : 'Active', name : 'active' }); return [ txt, num, combobox, datefield, chkbox //Step 2 ]; } });

In the first step we are creating our checkbox. We are using the boxLabel property to set the label of our checkbox; it's important to know that we are setting the fieldLabel and labelSeparator properties as an empty space. This way the checkbox will be aligned correctly.

In the last step we just add our new component to the returned array. The following screenshot shows our latest changes to the code:

Now we have our checkbox in place. Having a single checkbox is great, but there are times when we need to define a few more options. We can use a group of checkboxes to arrange the components horizontally, vertically, or in columns:

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', //... buildItems : function(){ //... //Step 1 var group = Ext.create('Ext.form.CheckboxGroup',{ fieldLabel : 'Languages', columns : 2, items : [ {name:'lan',boxLabel:'JavaScript',inputValue:'js'}, {name:'lan',boxLabel:'C/C++',inputValue:'c/cpp'}, {name:'lan',boxLabel:'Java',inputValue:'java'}, {name:'lan',boxLabel:'PHP',inputValue:'php'}, {name:'lan',boxLabel:'SQL',inputValue:'sql'}, {name:'lan',boxLabel:'Python',inputValue:'py'}, {name:'lan',boxLabel:'Ruby',inputValue:'rb'} ] }); return [txt,num,combobox,datefield,chkbox,group]; } });

In the first step we are creating an instance of the CheckboxGroup class. We defined the label of the group and gave each item a checkbox with its label and value. We are arranging the items in two columns.

In the last step we added the group to the returning array so it appears in our form:

The radio button

Radio buttons are useful when we want to force the user to select one item from a small group of choices. If we want to present more choices, a combobox is an easier widget to code and to use.

The radio button is very similar to the checkbox. In fact the radio button extends from the Checkbox class. This means the radio buttons also have the same properties and methods as the checkbox.

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', //... buildItems : function(){ //... var yes = Ext.create('Ext.form.field.Radio',{ name : 'option', fieldLabel : 'Are you a developer?', labelSeparator : '', boxLabel: 'Yes', inputValue : true }), no = Ext.create('Ext.form.field.Radio',{ name : 'option', fieldLabel : ' ', labelSeparator : '', boxLabel: 'No', inputValue : false }); return [txt,num,combobox,datefield,chkbox,group,yes,no]; } });

We are creating two instances of the Radio class exactly the same as we created the Checkbox class. In the creation of the Checkbox class we added two radio buttons to the returning array.

The following screenshot shows how the two radios were created:

It is important to assign the same name to the radio buttons so that only one option can be selected among the available ones.

As we can see in the previous screenshot the radios are arranged one over the other, but what if we want to align them horizontally? We can use a radiogroup component and set the number of columns as two. That way we will have our two radio buttons in the same line:

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', //... buildItems : function(){ //... var radiogroup = { xtype : 'radiogroup', columns : 2, fieldLabel: 'Are you a developer?', items : [yes,no] }; return [txt,num,combobox,datefield,chkbox,group,radiogroup]; } });

This is very similar to what we did with the checkbox group. We can define as many radio buttons as we need, and all of them will be arranged in two columns as shown in the following screenshot:

Learning Ext JS 4 Sencha Ext JS for a beginner book and ebook.
Published: January 2013
eBook Price: £18.99
Book Price: £30.99
See more
Select your format and quantity:

The field container

There are times when we need to group textfields or any other components other than checkbox and radio buttons. We can use the field container to group any type of field.

One of the advantages of using a field container is the ability to use a layout; we can use any of the available layouts in the framework.

The following code shows how we can group a textfield and a combobox to show these fields in the same line. We need to edit our previous code to add a few configurations to the price and size fields:

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', //... buildItems : function(){ //... //Step 1 var num = Ext.create('Ext.form.field.Number',{ emptyText : 'Price', name : 'price', step : 10, minValue : 30, maxValue : 100, flex : 1, margins : '0 5 0 0' //hideTrigger : true }); //... //Step 1 varcombobox = Ext.create('Ext.form.ComboBox',{ emptyText : 'Size', name : 'size', store : store, queryMode : 'local', displayField: 'label', valueField : 'key', forceSelection : true, flex : 1 }); //... //Step 2 varpricesize = { xtype : 'fieldcontainer', fieldLabel : 'Price/Size', layout : 'hbox', items : [num,combobox] }; return [txt, pricesize //Step 3 ,datefield,chkbox,group,container]; } });

In the first step we have removed the fieldLabel property and instead we defined the emptyText property, this way the label will be shown only when the field is empty. Also we have defined the flex property to make it flexible.

In the second step we created the field container with an hbox layout. This way the two fields will be flexible and grouped horizontally.

Finally, in the third step we removed the price and the size from the array and added the group. The following screenshot shows the changes in our code:

This is how we can arrange the fields in any way we want; using the field container is a great way to accomplish this task.

We can add as many components as we need, we can use any of the available layouts, the possibilities are endless.

Submitting the data

So far we have learned how to create and configure the components to collect data using the available widgets, but we need to do something with it. Ext JS provides different ways to submit the captured data to our server.

The Ext.form.Panel class contains an instance of the Ext.form.Basic class. This class is used to manage the data within the form, such as validations, settings and retrieving data to the fields, submitting and loading data from the server, and so on.

In order to send the data to the server we can use the submit method from the basic form. Let's add a button to our form and then submit the entered data to our server:

Ext.define('MyApp.view.AvailableFields',{ extend : 'Ext.form.Panel', //... initComponent : function(){ var me = this; me.items = me.buildItems(); //Step 1 me.tbar = [{text:'Save',handler:me.saveData,scope:me}]; me.callParent(); }, buildItems : function(){ //... }, //Step 2 saveData : function(){ var me = this; me.getForm().submit({ url : 'serverside/save.do', success : function(form,action){ Ext.Msg.alert('Success','Successfully saved'); }, failure : function(form,action){ Ext.Msg.alert('Failure','Something is wrong'); } }); } });

In the first step we defined a top toolbar with one button on it. When the button is clicked, the saveData function is executed.

In the second step we defined the saveData function. In this function we get the basic form and then execute the submit method. This method receives an object with the URL, where the Ajax request will be made, and the success/failure callback:

As shown in the previous screenshot the submit method executes an Ajax request using the POST method and sends all the entered data by the user. The way we get these parameters on the server side depends on the technology that we are using; for example if we are using PHP, we can do something like the following code:

<?php $firstname = $_POST['firstname']; $price = $_POST['price'];

If we are using Java, we probably would do something like the following code:

String firstname = request.getParameter("firstname"); String size = request.getParameter("size");

This depends on the framework, language, or technology that we use in the server side; the important thing is that Ext submits the data using the POST method and each parameter is sent using the name of the field.

The server code provided here is just an example and is not complete. The implementation of that is out of the scope of this book. However, based on the received data you can take that information and do whatever you need to do with it.

Summary

In this article we have learned about the forms and fields that we can use to collect and edit data. We have many options and configurations available that we can use to customize our forms.

The field container is one of the new components added to Version 4 of the Ext JS framework. This allows us to arrange the fields using any of the available layouts in the framework giving us a powerful layout system.

Resources for Article :


Further resources on this subject:


About the Author :


Armando Gonzalez

Armando Gonzalez is a Software Engineer with more than 4 years of experience in developing enterprise applications with Ext JS. He has plenty of experience in server-side technologies like PHP, Java J2EE, Node JS, and ROR. Before he started with Ext JS he was a Java and PHP developer.

Since he started using JavaScript and Ext JS he became a JavaScript Evangelist, and started training teams on JavaScript and Ext JS. He loves to teach and share his knowledge with other developers and is always trying to make them use this awesome library.

In early 2012 Armando started a software company, Codetlan, with some of his friends. This company focuses on developing enterprise applications using Sencha technologies. He is also a minor actionist in a Mexican startup called Cursame, where he developed the mobile version of the application and helped developing the main application using ROR technologies.

If you want to know more about his work, you can follow him on Twitter (@manduks) or can watch his Open Source projects on Github (manduks).

Crysfel Villa

Crysfel Villa is a Software Engineer with more than 7 years of experience with JavaScript on a daily basis. He started his career as a Web Developer working with HTML and basic JavaScript in the late nineties, but then he started focusing on Server Side technologies, such as PHP and Java J2EE.

Before he started working with the Ext JS library he loved to work with MooTools, but in late 2007 he started learning about an awesome new library that was emerging as an Open Source project. At that time the version 2.0 of the Ext JS library was just coming out and Crysfel started using this new library for medium-large projects in the agency that he used to work with.

In early 2010 Crysfel started working as a freelancer, he began to train teams on Ext JS for private companies, writing a blog with tutorials, tips and tricks, developing custom components on Ext JS for his clients, and working on Open Source projects to share his knowledge with the world.

If you want to find more information about his work, you can follow him on Twitter (@crysfel) or download his Open Source projects from GitHub (crysfel).

Books From Packt


Ext JS 4 First Look
Ext JS 4 First Look

Oracle Application Express 4.0 with Ext JS
Oracle Application Express 4.0 with Ext JS

Ext.NET Web Application Development
Ext.NET Web Application Development

Sencha Touch Mobile JavaScript Framework
Sencha Touch Mobile JavaScript Framework

Learning Ext JS 3.2
Learning Ext JS 3.2

Ext JS 3.0 Cookbook
Ext JS 3.0 Cookbook

Learning Ext JS
Learning Ext JS

Ext JS 4 Web Application Development Cookbook
Ext JS 4 Web Application Development Cookbook


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software