(For more resources related to this topic, see here.)
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.
Make sure that you have set up your development environment.
Carry out the following steps to create a form panel:
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: 'you@sencha.com',
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);
}
});
<script type="text/javascript" charset="utf-8"
src = "ch02/ch02_01.js"></script >
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:
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.
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.
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.
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.
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.
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({
...
...
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: 'ajit@wtc.com'
});
}
},
{
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:'ajit@wtc.com'
});
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:'ajit@wtc.com'
});
var formBase = {
scroll: 'vertical',
standardSubmit: true,
record: ajit,
...
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.
Make sure that you have set up your development.
Carry out the following steps:
var formBase = {
items: [{
xtype: 'searchfield',
name: 'search',
label: 'Search'
}]
};
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.
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.
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...'
}
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.
Make sure that you have set up your development environment.
Carry out the following steps:
and replace the definition of formBase with the following code:
var formBase = {
items: [{
xtype: 'emailfield',
name : 'email',
label: 'Email',
placeHolder: 'you@sencha.com',
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!!");
}
}
}]
};
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.
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.
Make sure that you have set up your development environment.
Carry out the following steps:
var formBase = {
items: [{
xtype: 'datepickerfield',
name: 'date',
label: 'Date'
}]
};
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.
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.
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(),
…
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},
…
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']}
}]
};
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}
}]
};
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.
Make sure that you have set up your development environment.
Carry out the following steps:
var formBase = {
items: [{
xtype: 'datepickerfield',
id: 'datefield-id',
name: 'date',
hidden: true,
label: 'Date'}]
};
When a field is marked as hidden, Sencha Touch uses the DOM’s hide() method on the element to hide that particular field.
Let’s see how we can programmatically show/hide a field.
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().
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.
Make sure that you have set up your development environment.
Carry out the following steps:
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'}
]
}]
};
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.
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.
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'}
]
}
This recipe describes the use of the slider form field, which allows the user to change the value by mere sliding.
Make sure that you have set up your development environment.
Carry out the following steps:
var formBase = {
items: [{
xtype: 'sliderfield',
name : 'height',
label: 'Height',
minValue: 0,
maxValue: 100,
increment: 10
}]
};
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.
I remember deciding to pursue my first IT certification, the CompTIA A+. I had signed…
Key takeaways The transformer architecture has proved to be revolutionary in outperforming the classical RNN…
Once we learn how to deploy an Ubuntu server, how to manage users, and how…
Key-takeaways: Clean code isn’t just a nice thing to have or a luxury in software projects; it's a necessity. If we…
While developing a web application, or setting dynamic pages and meta tags we need to deal with…
Software architecture is one of the most discussed topics in the software industry today, and…