Guide applies to: classic

Forms

A Form Panel is nothing more than a basic Panel with form handling abilities added. Form Panels can be used throughout an Ext application wherever there is a need to collect data from the user.

In addition, Form Panels can use any Container Layout, providing a convenient and flexible way to handle the positioning of their fields. Form Panels can also be bound to a Model, making it easy to load data from and submit data back to the server.

Under the hood a Form Panel wraps a Basic Form which handles all of its input field management, validation, submission, and form loading services. This means that many of the config options of a Basic Form can be used directly on a Form Panel.

Basic Form Panel

To start off, here’s how to create a simple Form that collects user data:

Expand Code

JS Run

  1. Ext.create('Ext.form.Panel', {
  2. renderTo: document.body,
  3. title: 'User Form',
  4. height: 350,
  5. width: 300,
  6. bodyPadding: 10,
  7. defaultType: 'textfield',
  8. items: [
  9. {
  10. fieldLabel: 'First Name',
  11. name: 'firstName'
  12. },
  13. {
  14. fieldLabel: 'Last Name',
  15. name: 'lastName'
  16. },
  17. {
  18. xtype: 'datefield',
  19. fieldLabel: 'Date of Birth',
  20. name: 'birthDate'
  21. }
  22. ]
  23. });

This Form renders itself to the document body and has three Fields - “First Name”, “Last Name”, and “Date of Birth”. Fields are added to the Form Panel using the items configuration.

The fieldLabel configuration defines what text will appear in the label next to the field, and the name configuration becomes the name attribute of the underlying HTML field.

Notice how this Form Panel has a defaultType of ‘textfield’. This means that any of its items that do not have an xtype specified (the “First Name” and “Last Name” fields in this example), are Text Fields.

The “Date of Birth” field, on the other hand, has its xtype explicitly configured as ‘datefield’, which makes it a Date Field. Date Fields expect to only contain valid date data and come with a DatePicker for selecting a date.

Fields

Field Types

Ext JS provides a set of standard Field types out of the box. Any of the Fields in the Ext.form.field namespace can be used in a Form Panel. For more information see the API documentaion for each Field type:

Validation

1. Built-in Validations

Ext JS has built in support for validation on any type of Field, and some Fields have built in validation rules.

For example, if a value is entered into a Date Field and that value cannot be converted into a Date, the Field will have the x-form-invalid-field CSS class added to its HTML element.

If necessary, this CSS class can be changed using the invalidCls configuration. Adding the invalidCls adds a red border to the input field (as well as a red “invalid underline” decoration when using the Classic theme):

Invalid Field

A Field containing invalid data will also display an error message. By default this message displays as a tool tip:

Invalid Field Hover

It’s easy to change the location of a Field’s error message using the msgTarget configuration, and the invalidText configuration changes the error message.

Each Field provides its own implementation of invalidText, and many support token replacement in the error message.

For example, in a Date Field’s invalidText, any occurrences of “{0}” will be replaced with the Field’s value, and any occurrences of “{1}” will be replaced with the required date format.

The following code demonstrates placing the error message directly under the Field, and customizing the error message text:

  1. {
  2. xtype: 'datefield',
  3. fieldLabel: 'Date of Birth',
  4. name: 'birthDate',
  5. msgTarget: 'under', // location of the error message
  6. invalidText: '"{0}" bad. "{1}" good.' // custom error message text
  7. }

Custom Error Message

2. Custom Validations

Some validation requirements cannot be met using the built-in validations. The simplest way to implement a custom validation is to use the Text Field‘s regex configuration to apply validation rules and the maskRe configuration to limit which characters can be typed into the field. Here’s an example of a Text Field that validates a time.

  1. {
  2. xtype: 'textfield',
  3. fieldLabel: 'Last Login Time',
  4. name: 'loginTime',
  5. regex: /^([1-9]|1[0-9]):([0-5][0-9])(\s[a|p]m)$/i,
  6. maskRe: /[\d\s:amp]/i,
  7. invalidText: 'Not a valid time. Must be in the format "12:34 PM".'
  8. }

While the above method works well for validating a single field, it is not practical for an application that has many fields that share the same custom validation.

The Ext.form.field.VTypes class provides a solution for creating reusable custom validations. Here’s how a custom “time” validator can be created:

  1. // custom Vtype for vtype:'time'
  2. var timeTest = /^([1-9]|1[0-9]):([0-5][0-9])(\s[a|p]m)$/i;
  3. Ext.apply(Ext.form.field.VTypes, {
  4. // vtype validation function
  5. time: function(val, field) {
  6. return timeTest.test(val);
  7. },
  8. // vtype Text property: The error text to display when the validation function returns false
  9. timeText: 'Not a valid time. Must be in the format "12:34 PM".',
  10. // vtype Mask property: The keystroke filter mask
  11. timeMask: /[\d\s:amp]/i
  12. });

Once a custom validator has been created it can be used on Text Fields throughout an application using the vtype configuration:

  1. {
  2. fieldLabel: 'Last Login Time',
  3. name: 'loginTime',
  4. vtype: 'time'
  5. }

See Validation Example for a working demo. For more information on custom validations, please refer to the API Documentation for VTypes.

Handling Data

Submitting a Form

The simplest way to submit data to the server is to use the url configuration of Basic Form. Since Form Panel wraps a Basic Form, we can use any of Basic Form’s configuration options directly on a Form Panel:

  1. Ext.create('Ext.form.Panel', {
  2. ...
  3. url: 'add_user',
  4. items: [
  5. ...
  6. ]
  7. });

The Form’s submit method can be used to submit data to the configured url:

  1. Ext.create('Ext.form.Panel', {
  2. ...
  3. url: 'add_user',
  4. items: [
  5. ...
  6. ],
  7. buttons: [
  8. {
  9. text: 'Submit',
  10. handler: function() {
  11. var form = this.up('form'); // get the form panel
  12. if (form.isValid()) { // make sure the form contains valid data before submitting
  13. form.submit({
  14. success: function(form, action) {
  15. Ext.Msg.alert('Success', action.result.msg);
  16. },
  17. failure: function(form, action) {
  18. Ext.Msg.alert('Failed', action.result.msg);
  19. }
  20. });
  21. } else { // display error alert if the data is invalid
  22. Ext.Msg.alert('Invalid Data', 'Please correct form errors.')
  23. }
  24. }
  25. }
  26. ]
  27. });

In the above example, a button is configured with a handler that handles form submission. The handler takes the following actions:

  1. First, a reference to the Form Panel must be acquired.
  2. Then the isValid method is called before submission to verify that none of the Fields have validation errors.
  3. Finally the submit method is called, and two callback functions are passed - success and failure. Within these callback functions, action.result refers to the parsed JSON response.

The above example expects a JSON response that looks something like this:

  1. { "success": true, "msg": "User added successfully" }

Binding a Form to a Model

The Model class is used throughout Ext JS for representing various types of data as well as retrieving and updating data on the server. A Model representing a User would define the fields a User has as well as a proxy for loading and saving data:

  1. Ext.define('MyApp.model.User', {
  2. extend: 'Ext.data.Model',
  3. fields: ['firstName', 'lastName', 'birthDate'],
  4. proxy: {
  5. type: 'ajax',
  6. api: {
  7. read: 'data/get_user',
  8. update: 'data/update_user'
  9. },
  10. reader: {
  11. type: 'json',
  12. root: 'users'
  13. }
  14. }
  15. });

Data can be loaded into a Form Panel directly from a Model using the loadRecord method:

  1. MyApp.model.User.load(1, { // load user with ID of "1"
  2. success: function(user) {
  3. userForm.loadRecord(user); // when user is loaded successfully, load the data into the form
  4. }
  5. });

Finally, instead of using the submit method to save the data, Form Panel’s updateRecord method is used to update the record with the form data, and the Model’s save method is called to save the data to the server:

  1. Ext.create('Ext.form.Panel', {
  2. ...
  3. url: 'add_user',
  4. items: [
  5. ...
  6. ],
  7. buttons: [
  8. {
  9. text: 'Submit',
  10. handler: function() {
  11. var form = this.up('form'), // get the form panel
  12. record = form.getRecord(); // get the underlying model instance
  13. if (form.isValid()) { // make sure the form contains valid data before submitting
  14. form.updateRecord(record); // update the record with the form data
  15. record.save({ // save the record to the server
  16. success: function(user) {
  17. Ext.Msg.alert('Success', 'User saved successfully.')
  18. },
  19. failure: function(user) {
  20. Ext.Msg.alert('Failure', 'Failed to save user.')
  21. }
  22. });
  23. } else { // display error alert if the data is invalid
  24. Ext.Msg.alert('Invalid Data', 'Please correct form errors.')
  25. }
  26. }
  27. }
  28. ]
  29. });

Model Binding Example

Layouts

Layouts are used to handle sizing and positioning of components in an Ext JS application. Form Panels can use any Container Layout. For more information on Layouts please refer to the Layouts and Containers Guide.

For example, positioning Fields in a form horizontally can easily be done using an HBox Layout:

Expand Code

JS Run

  1. Ext.create('Ext.form.Panel', {
  2. renderTo: document.body,
  3. title: 'User Form',
  4. height: 300,
  5. width: 585,
  6. defaults: {
  7. xtype: 'textfield',
  8. labelAlign: 'top',
  9. padding: 10
  10. },
  11. layout: 'hbox',
  12. items: [
  13. {
  14. fieldLabel: 'First Name',
  15. name: 'firstName'
  16. },
  17. {
  18. fieldLabel: 'Last Name',
  19. name: 'lastName'
  20. },
  21. {
  22. xtype: 'datefield',
  23. fieldLabel: 'Date of Birth',
  24. name: 'birthDate'
  25. }
  26. ]
  27. });