13 min read

(For more resources on Sencha Touch, see here.)

Most of the useful applications not only present the data, but also accept inputs from their users. When we think of having a way to accept inputs from the user, send them to the server for further processing, and allow the user to modify them, we think of forms and the form fields. If our application requires users to enter some information, then we go about using the HTML form fields, such as ,

Each field can be created by using the JSON notation ( JavaScript Object Notationhttp://www.json.org) or by creating an instance of the class. For example, a text field can either be constructed by using the following JSON notation:

{ xtype: ‘textfield’, name: ‘text’, label: ‘My Text’ }

Alternatively, we can use the following class constructor:

var txtField = new Ext.form.Text({ name: ‘text’, label: ‘My Text’ });

The first approach relies on xtype, which is a type assigned to each of the Sencha Touch components. It is used as shorthand for the class. The basic difference between the two is that the xtype approach is more for the lazy initialization and rendering. The object is created only when it is required. In any application, we would use a combination of these two approaches.

In this article, we will go through all the form fields and understand how to make use of them and learn about their specific behaviors. In addition, we will see how to create a form using one or more form fields and handle the form validation and submission.

Getting your form ready with FormPanel

This recipe shows how to create a basic form using Sencha Touch and implement some of the behaviors such as submitting the form data, handling errors during the submission, and so on.

Getting ready

Make sure that you have set up your development environment

How to do it…

Carry out the following steps:

    1. Create a ch02 folder in the same folder where we had created the ch01 folder.
    2. Create and open a new file named ch02_01.js and paste the following code into it:

Ext.setup({ onReady: function() { var form; //form and related fields config var formBase = { //enable vertical scrolling in case the form exceeds the page height scroll: ‘vertical’, url: ‘http://localhost/test. php’, items: [{//add a fieldset xtype: ‘fieldset’, title: ‘Personal Info’, instructions: ‘Please enter the information above.’, //apply the common settings to all the child items of the fieldset defaults: { required: true, //required field labelAlign: ‘left’, labelWidth: ‘40%’ }, items: [ {//add a text field xtype: ‘textfield’, name : ‘name’,

label: ‘Name’, useClearIcon: true,//shows the clear icon in the field when user types autoCapitalize : false }, {//add a password field xtype: ‘passwordfield’, name : ‘password’, label: ‘Password’, useClearIcon: false }, { xtype: ‘passwordfield’, name : ‘reenter’, label: ‘Re-enter Password’, useClearIcon: true }, {//add an email field xtype: ’emailfield’, name : ’email’, label: ‘Email’, placeHolder: ‘you@sencha.com’, useClearIcon: true }] } ], listeners : { //listener if the form is submitted, successfully submit : function(form, result){ console.log(‘success’, Ext.toArray(arguments)); }, //listener if the form submission fails exception : function(form, result){ console.log(‘failure’, Ext.toArray(arguments)); } }, //items docked to the bottom of the form dockedItems: [ { xtype: ‘toolbar’, dock: ‘bottom’, items: [ { text: ‘Reset’, handler: function() { form.reset(); //reset the fields

} }, { text: ‘Save’, ui: ‘confirm’, handler: function() { //submit the form data to the url form.submit(); } } ] } ] }; if (Ext.is.Phone) { formBase.fullscreen = true; } else { //if desktop Ext.apply(formBase, { autoRender: true, floating: true, modal: true, centered: true, hideOnMaskTap: false, height: 385, width: 480 }); } //create form panel form = new Ext.form.FormPanel(formBase); form.show(); //render the form to the body } });

 

    1. Include the following line in index.html:

    1. Deploy and access it from the browser. You will see the following screen:

How it works…

The code creates a form panel, with a field set inside it. The field set has four fields specified as part of its child items. xtype mentioned for each field instructs the Sencha Touch component manager which class to use to instantiate them.

form = new Ext.form.FormPanel(formBase) creates the form and the other field components using the config defined as part of the formBase.

form.show() renders the form to the body and that is how it will appear on the screen.

url contains the URL where the form data will be posted upon submission. The form can be submitted in the following two ways:

  1. By hitting Go, on the virtual keyboard or Enter on a field that ends up generating the action event.
  2. By clicking on the Save button, which internally calls the submit() method on the form object.

form.reset() resets the status of the form and its fields to the original state. Therefore, if you had entered the values in the fields and clicked on the Reset button, all the fields would be cleared.

form.submit() posts the form data to the specified url. The data is posted as an Ajax request using the POST method.

Use of useClearIcon on the field instructs Sencha Touch whether it should show the clear icon in the field when the user starts entering a value in it. On clicking on this icon, the value in the field is cleared.

There’s more…

In the preceding code, we saw how to construct a form panel, add fields to it, and handle events. We will see what other non-trivial things we may have to do in the project and how we can achieve these using Sencha Touch.

Standard submit

This is the old and traditional way for form data posting to the server url. If your application need is to use the standard form submit, rather than Ajax, then you will have to set standardSubmit to true on the form panel. This is set to false, by default. The following code snippet shows the usage of this property:

var formBase = { scroll: ‘vertical’, standardSubmit: true, …

After this property is set to true on the FormPanel, form.submit() will load the complete page specified in url.

Do not submit on field action

As we saw earlier, the form data is automatically posted to the url if the action event (when the Go or Enter key is hit) occurs. In many applications, this default feature may not be desirable. In order to disable this feature, you will have to set submitOnAction to false on the form panel.

Post-submission handling

Say we posted our data to the url. Now, either the call may fail or it may succeed. In order to handle these specific conditions and act accordingly, we will have to pass additional config options to the form’s submit() method. The following code shows the enhanced version of the submit call:

form.submit({ success: function(form, result) { Ext.Msg.alert(“INFO”, “Form submitted!”); }, failure: function(form, result) { Ext.Msg.alert(“INFO”, “Form submission failed!”); } });

If the Ajax call (to post form data) fails, then the failure callback function is called, and in the case of success, the success callback function is called. This works only if the standardSubmit is set to false.

Working with search

In this and the subsequent recipes of the article, we will go over each of the form fields and understand how to work with them. This recipe describes the steps required to create and use a search form field.

Getting ready

Make sure that you have set up your development environment.

Make sure that you have followed the Getting your form ready with FormPanel recipe.

How to do it…

Carry out the following steps:

    1. Copy ch02_01.js to ch02_02.js.
    2. Open a new file named ch02_02.js and replace the definition of formBase with the following code:

var formBase = { items: [{ xtype: ‘searchfield’, name: ‘search’, label: ‘Search’ }] };

  1. Include ch02_02.js in place of ch02_01.js in index.html.
  2. Deploy and access the application in the browser. You will see a form panel with a search field.

How it works…

The search field can be constructed by using the Ext.form.Search class instance or by using the xtype—searchfield. The search form field implements HTML5 with type=”search”. However, the implementation is very limited. For example, the HTML5 search field allows us to associate a data list to it which it can use during the search, whereas this feature is not present in Sencha Touch. Similarly, the W3 search field spec defines a pattern attribute to allow us to specify a regular expression against which a User Agent is meant to check the value, which is not supported yet in Sencha Touch. For more detail, you may refer to the W3 search field (http://www.w3.org/TR/html-markup/input.search.html) and the source code of the Ext.form.Search class.

There’s more…

Often, in the application, for the search fields we do not use a label. Rather, we would like to show a text, such as Search inside the field that will disappear when the focus is on the field. Let’s see how we can achieve this.

Using a placeholder

Placeholders are supported by most of the form fields in Sencha Touch by using the property placeHolder. The placeholder text appears in the field as long as there is no value entered in it and the field does not have the focus. The following code snippet shows the typical usage of it:

{ xtype: ‘searchfield’, name: ‘search’, label: ‘Search’, placeHolder: ‘Search…’ }

Putting custom validation in the e-mail field

This recipe describes how to make use of the e-mail form field provided by Sencha Touch and how to validate the value entered into it to find out whether the entered e-mail passes the validation rule or not.

Getting ready

Make sure that you have set up your development environment.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it…

Carry out the following steps:

    1. Copy ch02_01.js to ch02_03.js.
    2. Open a new file named ch02_03.js and replace the definition of formBase with the following code:

var formBase = { items: [{ xtype: ’emailfield’, name : ’email’, label: ‘Email’, placeHolder: ‘you@sencha.com’, useClearIcon: true, listeners: { blur: function(thisTxt, eventObj) { var val = thisTxt.getValue(); //validate using the pattern if (val.search(“[a-c]+@[a-z]+[.][a-z]+”) == -1) Ext.Msg.alert(“Error”, “Invalid e-mail address!!”); else Ext.Msg.alert(“Info”, “Valid e-mail address!!”);

} } }] };

  1. Include ch02_03.js in place of ch02_02.js in index.html.
  2. Deploy and access the application in the browser.

How it works…

The e-mail field can be constructed by using the Ext.form.Email class instance or by using the xtype: emailfield. The e-mail form field implements HTML5 with type=”email“. However, as with the search field, the implementation is very limited. For example, the HTML5 e-mail field allows us to specify a regular expression pattern which can be used to validate the value entered in the field.

Working with dates using DatePicker

This recipe describes how to make use of the date picker form field provided by Sencha Touch which allows the user to select a date.

Getting ready

Make sure that you have set up your development environment.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it…

Carry out the following steps:

    1. Copy ch02_01.js to ch02_04.js.
    2. Open a new file named ch02_04.js and replace the definition of formBase with the following code:

var formBase = { items: [{ xtype: ‘datepickerfield’, name: ‘date’, label: ‘Date’ }] };

  1. Include ch02_04.js in place of ch02_03.js in index.html.
  2. Deploy and access the application in the browser.

How it works…

The date picker field can be constructed by using the Ext.form.DatePicker class instance or by using xtype: datepickerfield. The date picker form field implements HTML

There’s more…

Additionally, there are other things that can be done such as setting the date to the current date, or any particular date, or changing the order of appearance of a month, day, and year. Let’s see what it takes to accomplish this.

Setting the default date to the current date

In order to set the default value to the current date, the value property must be set to the current date. The following code shows how to do it:

var formBase = { items: [{ xtype: ‘datepickerfield’, name: ‘date’, label: ‘Date’, value: new Date(),

Setting the default date to a particular date

The default date is 01/01/1970. Let’s assume that you need to set the date to a different date, but not the current date. To do so, you will have to set the value using the year, month, and day properties, as follows:

var formBase = { items: [{ xtype: ‘datepickerfield’, name: ‘date’, label: ‘Date’, value: {year: 2011, month: 6, day: 11}, …

Changing the slot order

By default, the slot order is month, day, and year. You can change it by setting the slotOrder property of the picker property of date picker, as shown in the following code:

var formBase = { items: [{ xtype: ‘datepickerfield’, name: ‘date’, label: ‘Date’, picker: {slotOrder: [‘day’, ‘month’, ‘year’]} }] };

Setting the picker date range

By default, the date range shown by the picker is 1970 until the current year. For our application need, if we have to alter the year range, we can do so by setting the yearFrom nd yearTo properties of the picker property of the date picker, as follows:

var formBase = { items: [{ xtype: ‘datepickerfield’, name: ‘date’, label: ‘Date’, picker: {yearFrom: 2000, yearTo: 2010} }] };

Making a field hidden

Often in an application, there would be a need to hide fields which are not needed in a particular context but are required and hence need to be shown in another. In this recipe, we will see how to make a field hidden and show it, conditionally.

Getting ready

Make sure that you have set up your development environment.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it…

Carry out the following steps:

    1. Edit ch02_04.js and modify the code as follows by adding the hidden property:

var formBase = { items: [{ xtype: ‘datepickerfield’, id: ‘datefield-id’, name: ‘date’, hidden: true, label: ‘Date’}] };

  1. Deploy and access the application in the browser.

How it works…

When a field is marked as hidden, Sencha Touch uses the DOM’s hide method on the element to hide that particular field.

There’s more…

Let’s see how we can programmatically show/hide a field.

Showing/Hiding a field at runtime

Each component in Sencha Touch supports two methods: show and hide. The show method shows the element and hide hides the element. In order to call these methods, we will have to first find the reference to the component, which can be achieved by either using the object reference or by using the Ext.getCmp() method. Given a component ID, the getCmp method returns us the component. The following code snippet demonstrates how to show an element:

var cmp = Ext.getCmp(‘datefield-id’); cmp.show();

To hide an element, we will have to call cmp.hide();


Subscribe to the weekly Packt Hub newsletter

* indicates required

LEAVE A REPLY

Please enter your comment!
Please enter your name here