ExtJS 4 表单

Form Panel表单面板就是普通面板Panel增加了表单处理能力。表单面板可以用在任何需要收集用户提交数据的地方。表单面板可以使用Container Layout提供的最简单的拜访表单控件的方式。表单面板可以和Model绑定,以方便加载和保存数据。其实表单面板包裹了Basic Form组件,Basic Form负责处理所有表单控件的管理,校验,提交和加载数据。这意味着所有Basic Form能接收的配置选项,都可以直接在表单面板上使用。

Basic Form Panel

开始我们演示一个可以简单的收集用户数据的表单:

 
Ext.create('Ext.form.Panel', {
    renderTo: Ext.getBody(),
    title: 'User Form',
    height: 130,
     280,
    bodyPadding: 10,
    defaultType: 'textfield',
    items: [
        {
            fieldLabel: 'First Name',
            name: 'firstName'
        },
        {
            fieldLabel: 'Last Name',
            name: 'lastName'
        },
        {
            xtype: 'datefield',
            fieldLabel: 'Date of Birth',
            name: 'birthDate'
        }
    ]
});

这个表单把自己渲染到document.body中,并且有三个表单字段- “First Name”, “Last Name”, 和 “Date of Birth”,表单字段是通过Form Panel的items配置添加的,fieldLabel配置表单字段旁边的文字标签,name配置表单字段对应的真实html表单字段的name。注意表单面板的默认类型defaultType属性是textfield。所有表单面板中不指定xtype的表单字段都将被当做textfield,例如例子中的First Name和Last Name,Date of Birth 通过xtype指定成了Date FieldDate Field是提供日期选框的控件。

Fields 表单字段

Field Types字段类型

ExtJS提供了一组标准字段,Ext.form.field命名空间里的组件都可以在表单面板中使用。具体可以参见api文档

  • Ext.form.field.Checkbox
  • Ext.form.field.ComboBox
  • Ext.form.field.Date
  • Ext.form.field.Display
  • Ext.form.field.File
  • Ext.form.field.Hidden
  • Ext.form.field.HtmlEditor
  • Ext.form.field.Number
  • Ext.form.field.Radio
  • Ext.form.field.Text
  • Ext.form.field.TextArea
  • Ext.form.field.Time
Validation 校验
1. Built-in Validations 内置校验

ExtJS的每一种表单字段都有内置校验,一些字段有内置规则。例如,如果一个不能转换成日期类型的值输入到日期字段中,x-form-invalid-field CSS class会加到字段的html结构中,以突出显示字段上的错误,这个CSS class可以由字段的invalidCls自定义。默认样式是红框:

ExtJS 4 表单

有错误的字段也会显示错误信息,默认的方式是tips提示

ExtJS 4 表单

可以通过msgTarget改变错误信息的显示位置,通过invalidText改变错误信息的内容,每个字段都有自己的invalidText实现方式,错误信息中有许多可替换的标记。例如,在Date Field的invalidText中,任何’{0}’ 都会被替换成这个字段的值,’{1}’会被替换成这个字段的format,下面的代码展示了如何使用这个特性自定义错误信息

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

ExtJS 4 表单

2. Custom Validations 定制校验

有些时候内置校验不能满足需求。最简单的方法就是实现自定义校验,使用Text Fieldregex配置应用一个校验规则,和使用maskRe配置限制可输入的字符,这有一个使用TextField校验输入时间的例子:

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

上面的方法对单个字段工作良好,但是应用中如果存在很多个需要相同校验方式的字段,这种方法就不是很方便了。Ext.form.field.VTypes提供了解决方案,通过它可以创建可复用的校验器,下面展示一下如何创建time校验器:

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

自定义校验器创建好之后,表单字段就可以通过vtype配置来调用:

 
{
    fieldLabel: 'Last Login Time',
    name: 'loginTime',
    vtype: 'time'
}

Handling Data 处理数据

Submitting a Form 如何提交表单

最简单的提交数据到服务器端的办法就是设置BasicFormurl配置,因为Form Panel封装了BasicForm,这个url直接配置给Form Panel亦可,它会透传给BasicForm的。

 
Ext.create('Ext.form.Panel', {
    ...
    url: 'add_user',
    items: [
        ...
    ]
});

BasicFormsubmit方法可以把数据提交到配置的url上:

 
Ext.create('Ext.form.Panel', {
    ...
    url: 'add_user',
    items: [
        ...
    ],
    buttons: [
        {
            text: 'Submit',
            handler: function() {
                var form = this.up('form').getForm(); // get the basic form
                if (form.isValid()) { // make sure the form contains valid data before submitting
                    form.submit({
                        success: function(form, action) {
                           Ext.Msg.alert('Success', action.result.msg);
                        },
                        failure: function(form, action) {
                            Ext.Msg.alert('Failed', action.result.msg);
                        }
                    });
                } else { // display error alert if the data is invalid
                    Ext.Msg.alert('Invalid Data', 'Please correct form errors.')
                }
            }
        }
    ]
});

上面的例子中,button配置了一个处理函数用来处理表单提交,处理函数中做了下面几个动作:

  1. 首先找到对BasicForm的引用
  2. 提交之前调用了isValid方法确保每个表单字段都已经填写正确
  3. 最后调用submit方法,并传递了两个回调函数successfailure,在这两个回调函数的参数中,action.result可以引用到服务器端返回JSON的解析后的对象

像例子中的表单提交,期望服务器端返回的值,应该像这样:

1
{ "success": true, "msg": "User added successfully" }
Binding a Form to a Model 如何绑定表单和模型

ExtJS中,模型用来定义各种数据,也可以加载和保存数据到服务器。例如一个User模型需要定义User的字段,同时也可以设置代理用来加载和保存数据:

 
Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: ['firstName', 'lastName', 'birthDate'],
    proxy: {
        type: 'ajax',
        api: {
            read: 'data/get_user',
            update: 'data/update_user'
        },
        reader: {
            type: 'json',
            root: 'users'
        }
    }
});

有关模型的更多内容请查看<ExtJS 4 数据(包)详解>

数据可以通过loadRecord方法直接从Model加载进入Form Panel

 
Ext.ModelMgr.getModel('User').load(1, { // load user with ID of "1"
    success: function(user) {
        userForm.loadRecord(user); // when user is loaded successfully, load the data into the form
    }
});

最后,代替submit方法,可以使用BasicFormupdateRecord方法更新form绑定的model,然后用Model的save方法保存数据:

 
Ext.create('Ext.form.Panel', {
    ...
    url: 'add_user',
    items: [
        ...
    ],
    buttons: [
        {
            text: 'Submit',
            handler: function() {
                var form = this.up('form').getForm(), // get the basic form
                    record = form.getRecord(); // get the underlying model instance
                if (form.isValid()) { // make sure the form contains valid data before submitting
                    form.updateRecord(record); // update the record with the form data
                    record.save({ // save the record to the server
                        success: function(user) {
                            Ext.Msg.alert('Success', 'User saved successfully.')
                        },
                        failure: function(user) {
                            Ext.Msg.alert('Failure', 'Failed to save user.')
                        }
                    });
                } else { // display error alert if the data is invalid
                    Ext.Msg.alert('Invalid Data', 'Please correct form errors.')
                }
            }
        }
    ]
});

Layouts 表单布局

ExtJS应用布局管理组件的大小和位置,Form Panel可以应用任何Container Layout,有关布局的更多内容请查看<ExtJS 4 布局和容器>

例如横着拜访表单字段可以应用HBox布局:

 
Ext.create('Ext.form.Panel', {
    renderTo: Ext.getBody(),
    title: 'User Form',
    height: 100,
     515,
    defaults: {
        xtype: 'textfield',
        labelAlign: 'top',
        padding: 10
    },
    layout: {
        type: 'hbox'
    },
    items: [
        {
            fieldLabel: 'First Name',
            name: 'firstName'
        },
        {
            fieldLabel: 'Last Name',
            name: 'lastName'
        },
        {
            xtype: 'datefield',
            fieldLabel: 'Date of Birth',
            name: 'birthDate'
        }
    ]
});