ExtJS 4 表單

Form Panel表單面板就是普通面板Panel增長了表單處理能力。表單面板能夠用在任何須要收集用戶提交數據的地方。表單面板可使用Container Layout提供的最簡單的拜訪表單控件的方式。表單面板能夠和Model綁定,以方便加載和保存數據。其實表單面板包裹了Basic Form組件,Basic Form負責處理全部表單控件的管理,校驗,提交和加載數據。這意味着全部Basic Form能接收的配置選項,均可以直接在表單面板上使用。 html

Basic Form Panel

開始咱們演示一個能夠簡單的收集用戶數據的表單:ajax

 
Ext.create('Ext.form.Panel', {
    renderTo: Ext.getBody(),
    title: 'User Form',
    height: 130,
    width: 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是提供日期選框的控件。 json

Fields 表單字段

Field Types字段類型

ExtJS提供了一組標準字段,Ext.form.field命名空間裏的組件均可以在表單面板中使用。具體能夠參見api文檔 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自定義。默認樣式是紅框: 服務器

image

有錯誤的字段也會顯示錯誤信息,默認的方式是tips提示 app

image

能夠經過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
}

image

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: /[\d\s:amp]/i,
    invalidText: 'Not a valid time.  Must be in the format "12:34 PM".'
}

上面的方法對單個字段工做良好,可是應用中若是存在不少個須要相同校驗方式的字段,這種方法就不是很方便了。Ext.form.field.VTypes提供瞭解決方案,經過它能夠建立可複用的校驗器,下面展現一下如何建立time校驗器:ui

 
// 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: /[\d\s:amp]/i
});

自定義校驗器建立好以後,表單字段就能夠經過vtype配置來調用:this

 
{
    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,
    width: 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'
        }
    ]
});
相關文章
相關標籤/搜索