1、form提供了两种加载数据的方式,一个loadData方法加载model,一个是setValues方法加载对象。setValues方法我对其进行了简单的方法封装。
Ext.onReady(function () {
myform = Ext.create('Ext.form.Panel', {
title : 'Simple Form',
bodyPadding : 5,
width : 350,
layout : 'anchor',
frame : true,
defaults : {
anchor : '100%'
},
defaultType : 'textfield',
items : [{
fieldLabel : 'First Name',
name : 'first',
allowBlank : false
}, {
fieldLabel : 'Last Name',
name : 'last',
allowBlank : false
}
],
buttons : [{
text : '重置',
handler : function () {
this.up('form').getForm().reset();
}
}, {
text : '保存',
handler : function () {
var form = this.up('form').getForm();
if (form.isValid()) {
Logger.printf(11)
}
}
}
],
renderTo : Ext.getBody()
});
Ext.define('User',{
extend : Ext.data.Model,
fields: [
{name: 'first', type: 'string'},
{name: 'last', type: 'string'}
]
})
var UserModel = Ext.create('User');
UserModel = obj2model({first:'tom',last:'tom'},UserModel )
//loadRecord( Ext.data.Model record ) : Ext.form.Basic
//加载Ext.data.Model到该表单,通过调用setValues与record data。 See also trackResetOnLoad.
myform.loadRecord(UserModel)
//obj --> form : void
obj2form({last:'jerry',first:'lucy'},myform);
})
//obj --> form : void
function obj2form(obj,form){
if (Ext.isEmpty(obj) || !Ext.isObject(obj)) return;
var formArr = Ext.Object.getKeys(form.getValues());
var objArr = Ext.Object.getKeys(obj);
var o = {};
Ext.each(objArr,function(item){
if(Ext.Array.contains(formArr,item)){
o[item] = obj[item]||''
};
});
if(!Ext.isEmpty(o) && Ext.isObject(o))
form.getForm().setValues(o);
}
//obj--->model:model
function obj2model(obj, model) {
if (!model.isModel || Ext.isEmpty(obj) || !Ext.isObject(obj))
return null;
var keyarr = Ext.Object.getKeys(model.getData())
Ext.Object.each(obj, function (key, value, myself) {
if (Ext.Array.contains(keyarr, key)) {
if (Ext.isObject(value)) {
console.error('Objects can not contain objects');
return null;
}
model.set(key, value || '')
}
});
return model;
}
//记录器
Ext.define('Logger', {
singleton : true,
log : function (msg) {
console.log(msg);
},
error : function (msg) {
console.error(msg)
},
printferror : function (msg) {
this.error(Ext.id('', 'num:') + ' ' + msg);
},
printf : function (msg) {
this.log(Ext.id('', 'num:') + ' ' + msg);
},
printf2 : function (val, msg) {
this.printf(val + '--' + msg);
},
printfobj : function (obj) {
var s = '';
if (Ext.isObject(obj)) {
Ext.Object.each(obj, function (key, value, myself) {
s += key + ":" + (Ext.isObject(value) ? 'object' : value) + " ";
})
}
if (s)
this.printf(s);
},
printfarr : function (arr) {
var s = '';
Ext.each(arr, function (item) {
if (Ext.isObject(item)) {
Ext.Object.each(item, function (key, value, myself) {
s += key + ":" + (Ext.isObject(value) ? 'object' : value) + " ";
})
}
});
this.printf(s ? s : arr)
}
});