15 min read

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

Getting your form ready with form panels

This recipe shows how to create a basic form using Sencha Touch and implement some of the behaviors such as how to submit the form data and how to handle the errors during the submission.

Getting ready

Make sure that you have set up your development environment.

How to do it…

Carry out the following steps to create a form panel:

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

    Ext.application({
    name: 'MyApp',
    requires: ['Ext.MessageBox'],
    launch: function() {
    var form;
    //form and related fields config
    var formBase = {
    //enable vertical scrolling in case the form exceeds the page
    height
    scrollable: 'vertical',
    standardSubmit: false,
    submitOnAction: true,
    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 feild
    xtype: 'textfield',
    name : 'name',
    label: 'Name',
    clearIcon: true,//shows the clear icon in the field when user
    types
    autoCapitalize : true
    },
    { //add a password field
    xtype: 'passwordfield',
    name : 'password',
    label: 'Password',
    clearIcon: false
    }, {
    xtype: 'passwordfield',
    name : 'reenter',
    label: 'Re-enter Password',
    clearIcon: true
    }, { //add an email field
    xtype: 'emailfield',
    name : 'email',
    label: 'Email',
    placeHolder: '[email protected]',
    clearIcon: true
    }]
    }, {
    //items docked to the bottom of the form
    xtype: 'toolbar',
    docked: 'bottom',
    items: [
    {
    text: 'Reset',
    handler: function() {
    form.reset(); //reset the fields
    }
    },
    {
    text: 'Save',
    ui: 'confirm',
    handler: function() {
    //sumbit the form data to the url
    form.submit({
    success: function(form, result) {Ext.Msg.alert("INFO", "Form
    submitted!");},
    failure: function(form, result) {Ext.Msg.alert("INFO", "Form
    submission failed!");}
    });
    }
    }
    ]
    }
    ]
    };
    if (Ext.os.is.Phone) {
    formBase.fullscreen = true;
    } else { //if desktop
    Ext.apply(formBase, {
    modal: true,
    centered: true,
    hideOnMaskTap: false,
    height: 385,
    width: 480
    });
    }
    //create form panel
    form = Ext.create('Ext.form.Panel', formBase);
    Ext.Viewport.add(form);
    }
    });

  3. Include the following line of code in the index.html file:

    <script type="text/javascript" charset="utf-8"
    src = "ch02/ch02_01.js"></script >

  4. Deploy and access it from the browser. You will see a screen as shown in the following screenshot:

How it works…

The code creates a form panel with a fieldset inside it. The fieldset has four fields specified as part of its child items. The xtype config mentioned for each field tells 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. The form.show(); code renders the form to the body, and that’s 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 two ways:

  • By hitting Go on the virtual keyboard, or Enter on a field, which ends up generating the action event
  • 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. So, 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 tells Sencha Touch whether it should show the clear icon in the field when the user starts entering values in it. On clicking 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. Let us 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 an old and traditional way for posting form data to the server URL. If your application’s need is to use the standard form submit rather than Ajax, you will have to set the standardSubmit property 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 form panel, form.submit() will load the complete page specified in the url property.

Submitting on field action

As we saw earlier, the form data automatically gets posted to the URL if the action event occurs (when the Go button or the Enter key is hit). In many applications, this default feature may not be desirable. 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. 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!");
}
});

In case the Ajax call (to post form data) fails, the failure() callback function is called and if it’s successful, the success() callback function is called. This works only if the standardSubmit property is set to false.

Reading form data

To read the values entered into a form field, form panel provides the getValues() method, which returns an object with field names and their values. It is important that you set the name property on your form field otherwise that field value will not appear in the object returned by the getValues() method:

handler: function() {
console.log('INFO', form.getValues());
//sumbit the form data to the url
form.submit({
...
...

Loading data in the form fields

To set the form field values, the form panel provides record config and two methods, setValues() and setRecord(). The setValues() method expects a config object with name-value pairs for the fields. The following code shows how to use the setValues() method:

{
text: 'Set Data',
handler: function() {
form.setValues({
name:'Ajit Kumar',
email: '[email protected]'
});
}
},
{
text: 'Reset',
...
...

The preceding code adds a new button named Set Data; by clicking on it, the form field data is populated as shown in the following screenshot. As we had passed values for the Name and Email fields they are set:

The other method, setRecord(),expects an instance of the Ext.data.Model class. The following code shows how we can create a model and use it to populate the form fields:

,
{
text: 'Load Data',
handler: function() {
Ext.define('MyApp.model.User', {
extend: 'Ext.data.Model',
config: {
fields: ['name', 'email']
}
});
var ajit = Ext.create('MyApp.model.User', {
name:'Ajit Kumar',
email:'[email protected]'
});
form.setRecord(ajit);
}
},
{
text: 'Reset',
...
...

We shall use setRecord() when our data is stored as a model, or we will construct it as a model to use the benefits of the model (for example, loading from a remote data source, data conversion, data validation, and so on) that are not available with the JSON presentation of the data.

While the methods help us to set the field values at runtime the, record config allows us to populate the form field values when the form panel is constructed. The following code snippet shows how we can pass a model at the time of instantiation of the form panel:

var ajit = Ext.create('MyApp.model.User', {
name:'Ajit Kumar',
email:'[email protected]'
});
var formBase = {
scroll: 'vertical',
standardSubmit: true,
record: ajit,
...

Working with search

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.

How to do it…

Carry out the following steps:

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

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

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

How it works…

A search field can be constructed using the Ext.field.Search class instance or using the xtype: ‘searchfield’ approach. A search form field implements the HTML5 <input> element with type=”search”. However, the implementation is very limited. For example, the search field in HTML5 allows us to associate a data list that it can use during the search, whereas this feature is not present in Sencha Touch. Similarly, the W3 search field 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.field.Search class.

There’s more…

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

Using a placeholder

Placeholders are supported by most of the form fields in Sencha Touch using the placeholder property. 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...'
}

Applying 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.

How to do it…

Carry out the following steps:

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

    var formBase = {
    items: [{
    xtype: 'emailfield',
    name : 'email',
    label: 'Email',
    placeHolder: '[email protected]',
    clearIcon: 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!!");
    }
    }
    }]
    };

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

How it works…

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

Working with dates using the date picker

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.

How to do it…

Carry out the following steps:

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

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

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

How it works…

The date picker field can be constructed using the Ext.field.DatePicker class instance or using the xtype: datepickerfield approach. The date picker form field implements the HTML <select> element. When the user tries to select an entry, it shows the date picker component with the slots for the month, day, and year for selection. After selection, when the user clicks on the Done button, the field is set with the selected value.

There’s more…

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

Setting the default date to the current date

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 January 01, 1970. Let’s suppose 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 property 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 from 1970 till the current year. For our application need, if we have to alter the year range to a different range, then we can do so by setting the yearFrom and 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: 2013}
}]
};

Making a field hidden

Often in an application, there would be a need to hide the fields that are not needed in a particular context but are required, and hence they need to be shown. 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.

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'}]
    };

  2. 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 the hide() method hides the element. To call these methods, first we will have to 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 showing an element:

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

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

Working with the select field

This recipe describes the use of the select form field, which allows the user to select a value from a list of choices, such as a combobox.

Getting ready

Make sure that you have set up your development environment.

How to do it…

Carry out the following steps:

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

    var formBase = {
    items: [{
    xtype: 'selectfield',
    name: 'select',
    label: 'Select',
    placeHolder: 'Select...',
    options: [
    {text: 'First Option', value: 'first'},
    {text: 'Second Option', value: 'second'},
    {text: 'Third Option', value: 'third'}
    ]
    }]
    };

  3. Include ch02_05.js in place of ch02_04.js in index.html.
  4. Deploy and access the application in the browser.

How it works…

The preceding code creates a select form field with three options for selection. The select field can be constructed using the Ext.field.Select class instance or using the xtype: ‘selectfield’ approach. The select form field implements the HTML <select> element. By default, it uses the text property to show the text for selection.

There’s more…

It may not always be possible or desirable to use text and value properties in the date to populate the selection list. In case we have a different property in place of text, then how do we make sure that the selection list is populated correctly without any further conversion? Let’s see how we can do this.

Using a custom display value

We shall use displayField to specify the field that will be used as text, as shown in the following code:

{
xtype: 'selectfield',
name: 'select',
label: 'Second Select',
placeHolder: 'Select...',
displayField: 'desc',
options: [
{desc: 'First Option', value: 'first'},
{desc: 'Second Option', value: 'second'},
{desc: 'Third Option', value: 'third'}
]
}

Changing a value using slider

This recipe describes the use of the slider form field, which allows the user to change the value by mere sliding.

Getting ready

Make sure that you have set up your development environment.

How to do it…

Carry out the following steps:

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

    var formBase = {
    items: [{
    xtype: 'sliderfield',
    name : 'height',
    label: 'Height',
    minValue: 0,
    maxValue: 100,
    increment: 10
    }]
    };

  3. Include ch02_06.js in place of ch02_05.js in index.html.
  4. Deploy and access the application in the browser.

How it works…

The preceding code creates a slider field with 0 to 100 as the range of values, with 10 as the increment value; this means that, when a user clicks on the slider, the value will change by 10 on every click. The increment value must be a whole number.

LEAVE A REPLY

Please enter your comment!
Please enter your name here