Geeks With Blogs
Łukasz Kuryło's blog

This is a part of EXT JS Tutorial

In this article I will cover information about creating, submitting and validating a forms with Ext JS library.
Submitting form to the server will be based on ASP.NET MVC page, so create a new MVC project in Visual Studio and add a EXT JS library into it. How to do it I have written here. So let’s create our first form.

How to create a simple form – first example.

              var form = new Ext.form.FormPanel({ //(1)

                    renderTo: Ext.getBody(), //(2)

                    url: 'Home/SubmitForm',

                    frame: true,

                    title: 'Tell me sth about yourself',

                    width: 200,

                    items: [{ //(3)

                        xtype: 'textfield',

                        fieldLabel: 'Your name',

                        name: 'name'

                    }, {

                        xtype: 'numberfield',

                        fieldLabel: 'Age',

                        name: 'age'

              }]

                    });


Listing above shows:

            (1) FormPanel is used to group fields in a single panel. It corresponds to a <form> tag in XHTML. FormPanel takes one argument which is a config object.
            (2) In the config object you can specify the form properties, one by line in this example, but this is not required. You can write all in one line remembers only to separate them with a colon (,). Placing them one after another may improve readability.
            (3) All fields, like html textbox, combobox and other in FormPanel are definied as elements of the items collection. One record for one field. In EXT JS you can create these fields in two ways. Above is presented first. The second looks like:

           var nameTextField = new Ext.form.TextField({

                    fieldLabel: 'Your name',

                    name: 'name'

                });

                var ageNumberField = new Ext.form.NumberField({

                    fieldLabel: 'Age',

                    name: 'age'

                });

 

                var form = new Ext.form.FormPanel({ //(1)

                    renderTo: Ext.getBody(), //(2)

                    url: 'Home/SubmitForm',

                    frame: true,

                    title: 'Tell me sth about yourself',

                    width: 200,

                    items: [ //(3)

                nameTextField,

                ageNumberField

]

                });


In both situations the result looks the same:







Other fields

Except TextField and NumberField we can use:

-radio buttons

 

                    {

                        xtype: 'radio',

                        fieldLabel: 'Sex',

                        name: 'sex',

                        boxLabel: 'male'

                    }, {

                        xtype: 'radio',

                        name: 'sex',

                        hideLabel: false,

                        boxLabel: 'female'

                    }


Important is here to set the name to the same value. Thanks to it, it is possible to check the value in action method on the server.

-checkbox
 

 

                    {

                        xtype: 'checkbox',

                        name: 'siblings',

                        fieldLabel: 'Siblings'

                    }


-combobox

To combobox field are added pairs, with key and the value. The key can be read after submitting the form in the server side code, value this is what user can see in the browser when he selected one from the available options.
EXT provides special store objects, where data can be kept. This feature will be covered in one of the next parts.
At this point look only for below example, which is used to work with combobox field:

                var answers = new Ext.data.SimpleStore({

                    fields: ['id', 'answer'],

                    data: [['1', 'yes'], ['2', 'no']]

                });


and the combo:

                   {

                        xtype: 'combo',

                        store: answers,

                        mode: 'local',

                        fieldLabel: 'available answers',

                        name: 'answer',

                        anchor: '90%',

                        displayField: 'answer',

                        valueField: 'id'

                    }


As you can see, in the combo to the store config option is link the SimpleStore object with handle the data. To the displayField and valueField are assigned fields from used store.




-datefield

 

                    {

                        xtype: 'datefield',

                        name: 'date',

                        fieldLabel: 'Select date',

                        anchor: '90%',

                        disabledDays: [0,6]

                    }
















-timefield

                    {

                        xtype: 'timefield',

                        name: 'time',

                        fieldLabel: 'Time',

                        anchor: '90%'

                    }























-textarea

                    {

                        xtype: 'textarea',

                        name: 'area',

                        fieldLabel: 'Enter some text',

                        anchor: '90%',

                        multiline: true

                    }


Listeners

For each field in documentation you can find a lot of events. This is very easy to listen to them in EXT JS. Look at example of using a invalid event:

                var nameTextField = new Ext.form.TextField({

                    fieldLabel: 'Your name',

                    name: 'name',

                    allowBlank: false,

                    listeners: {

                        invalid: function(field, msg)

                        {

                            Ext.Msg.alert('', msg);

                        }

                    }

                });


In this code, when you leave blank the Name field, the error message you will see in the alert dialog instead of baloon.










Submitting form to the server

In previous paragraph I have showed how to create a form to take data from user. Now I would like to concentrate how to send and use these data in a server side code. To be able to send the data to the server, form must have a button to do that. FormPanel contain similar to the items collection, collection of buttons. Look at this code

               buttons: [{

                    text: 'Save',

                    handler: function()

                    {

                        form.getForm().submit({

                            success: function(a, b)

                            {

                                Ext.Msg.alert('Success', 'ok');

                            },

                            failure: function(a, b)

                            {

                                Ext.Msg.alert('Failure', b.result.error);

                            }

                        });

                    }

                }, {

                    text: 'Reset',

                    handler: function()

                    {

                        form.getForm().reset();

                    }

                 }]


In code below there are created two buttons, one for submit the form and one for reset it. Both have a handler methods. In handler method you can specify, what will be done when the button is pressed. In the Save button there is called the submit method and checked the result .
Before we can submit the form, we must create a action method in the controller class:

        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult SubmitForm(FormCollection collection)

        {

            string response = String.Empty;

            //validation here

            try

            {

                string name = collection.GetValue("name").AttemptedValue;

                int age = Convert.ToInt32(Request.Form["age"]);

                response = "{success: true}";

            }

            catch (Exception)

            {

                response = "{success: false, error: \”an error occurred\”}";

            }

            return Content(response);

        }


In this code, in action method the submitted data should be validated if it hasn’t been done in the client code. The next two paragraphs are devoted to client side validation.

Developer can determine in the submit method, if the result is successful or not. Both, success and failure takes two arguments, which determine: the first is the form that requested this action, the second: the response from the server.

Build-in validation

At this point when you click the Save button, everything seems to work fine. However in the fields for name and age you can almost insert whatever you want. That’s true, in the numberfield you can insert only numbers, but these numbers can be negative too. Negative age it isn’t something what we want.












As I mentioned earlier, you can validate these fields on the server, but better way would seem to be validate it from the client side. EXT JS provides the stuff to do it. Suppose that, we would like to have the possibility to insert into the Name field only a alphabetic characters and this field must have a value (can’t be empty). For validation we can use a build-in vtype types. We can distinguish the basics: url, email, alpha and alphanum. These names are so obvious that I don't need to describe them, I think . Ok, it’s time to show how to use them

                var nameTextField = new Ext.form.TextField({

                    fieldLabel: 'Your name',

                    name: 'name',

                    vtype: 'alpha',

                    allowBlank: false

                });


As you can see I added two new lines. Thanks to the first line you can not add anything that is not a sign from the alphabet now. Second defines that, the field can’t be empty. When you try to submit the form without the value in the Name field, you will see an error










The field in underlined and nothing else. You can customize it by adding a new line

            Ext.QuickTips.init();


just under the Ext.onReady function. Using it, when you mouse over the field, you will see a balloon with the message showing what went wrong












To validate an Age field you can use config options, like maxValue, allowNegative, allowDecimals, allowBlank and minValue.

               var ageNumberField = new Ext.form.NumberField({

                    fieldLabel: 'Age',

                    name: 'age',

                    maxValue: 100,

                    allowNegative: false,

                    allowDecimals: false,

                    allowBlank: false,

                    minValue: 10

               });


Custom validation

Using EXT JS you can create your own, custom validation. The build-in vtypes are very limited. For example in the field where user must write his name, there are available only characters from ASCII, or in other words only characters which appear in English alphabet. In this situation I’m not able to put there my name, which contains polish specified characters. Everyone with different locale that English will be have this problem.
To create a custom vtype we need to add it to the vtype definition. Lets see an example. This code allows to use a polish letters in the TextField, additionally the first letter for surname and first for firstname will be capitalized.

                Ext.form.VTypes['ValidNameVal'] = //(1)

                        /^[A-ZLZ][A-ZZLSZa-zaleózzncs\-]+ [A-ZLZ][A-ZZLSZa-zaleózzncs\-]+$/;

                Ext.form.VTypes['ValidNameMask'] = /[A-ZZLSZa-zaleózzncs\- ]/; //(2)

                Ext.form.VTypes['ValidNameText'] = 'Invalid name'; //(3)

                Ext.form.VTypes['ValidName'] = function(arg) //(4)

                {

                    return Ext.form.VTypes['ValidNameVal'].test(arg);

                }


At first glance it may look horrible. Especially because of the used regular expression (regex) if you are not familiar with this syntax. Each vtype definition has a:

            (1) Value – here is the regex to match to the user input
            (2) Mask – here are specified characters, which user can input in the field,
            (3) Text – this is the message with the error description
            (4) The last require element – the function for testing

Below example shows how it look like in the web browser. To use this custom vtype, you must change the definition for TextField from

            var nameTextField = new Ext.form.TextField({

                fieldLabel: 'Your name',

                name: 'name',

                vtype:alpha,

                allowBlank: false

            });


to

               var nameTextField = new Ext.form.TextField({

                    fieldLabel: 'Your name',

                    name: 'name',

                    vtype: 'ValidName',

                    allowBlank: false

                });


Result










As you can see, with polish letters I have no problem any more. If error occur (first letter for my surname is not capitalize) , validation works properly:










Summary

In this part I have covered how to work with forms using the EXT JS library and ASP.NET MVC. I’ve showed how to create, validate and submit them to the server. And at the end the possibility of creating own custom validation. That’s not all what is related to forms in this library. In next parts there will be explained how to create and use them with the layouts, further will be showed how to work with data stores and other.
The source code with above examples is available here (click the blue button called "Pobierz plik").


Posted on Sunday, September 13, 2009 6:26 PM Ext JS Tutorial | Back to top


Comments on this post: Forms with EXT JS

# re: Forms with EXT JS
Requesting Gravatar...
Thank you for taking the time to post this.
It was very helpful.
Left by Steven Benjamin on Sep 29, 2009 3:07 AM

# re: Forms with EXT JS
Requesting Gravatar...
your scripts are very helpful.
Am new to extjs how do i load a form from a button e.g company details button to get the form where all company details are?
Left by wycliffe on Feb 11, 2010 3:06 PM

# re: Forms with EXT JS
Requesting Gravatar...
In any xtype you have defined, you dint used id property to any type.

I want to know, if an xtype is already defined, say pagination toolbar, then how can i target specific element in that ?
Is it possible to pass id config when using xtype in config ? like
xtype : 'myForm',
id : 'myId',
i think no, because xtype returns a UI component,and we cannot give an id to its inner component. but a id can be given to the component itself.
Left by justin on May 07, 2010 10:27 AM

# re: Forms with EXT JS
Requesting Gravatar...
Hello from turkey
Samples project asp.net + coolite + n-tier
Left by celalettin on Jun 14, 2010 12:25 PM

# re: Forms with EXT JS
Requesting Gravatar...
Compliments for your website. I am using Extjs intensive now, but your overview is helping me still.
Left by Johan van de Merwe on Aug 08, 2010 12:16 AM

# re: Forms with EXT JS
Requesting Gravatar...
this explanation about forms in extjs is very good and i understood very clearly thanks for that hope u publish more about extjs
Left by mvvsatyanarayana on Dec 05, 2010 5:41 PM

# re: Forms with EXT JS
Requesting Gravatar...
hi
How to read store into textfield on extjs?
and Displaying Data From textfield
Left by hasti on Feb 27, 2011 8:27 AM

# re: Forms with EXT JS
Requesting Gravatar...
Hi, how do I put 'strange characters' in a combobox? I have this now, but does'nt show content in dropdown:

store: Ext.create('Ext.data.Store', {
fields : ['name', 'Value'],
data : [ {name : '<=', value: '<='},
{name : '==', value: '=='}, {name : '=>', value: '=>'}, {name : '<', value: '<'},
{name : '>', value: '>'},
]
}
Left by Robine on May 20, 2011 3:05 PM

Comments have been closed on this topic.
Copyright © Łukasz Kuryło | Powered by: GeeksWithBlogs.net