這個範例示範了 ExtJS 最典型的用法:把每個 UI 元件獨立定義成變數,再像積木一樣組進 Viewport。從查詢列、資料格到彈出式編輯表單,一次走過。
畫面用 border layout 切兩塊:pnNorth 是北側查詢工具列,pnCenter 是中央的商品列表。雙擊任一列會跳出 winProductInfo 視窗,裡頭用 TabPanel 分頁承載「商品資訊」與「相關種類資訊」兩組表單。
var dtCategory = [
['all','所有種類'], ['1','Beverages'], ['2','Condiments'], ['3','Confections'],
['4','Dairy Products'], ['5','Grains/Cereals'], ['6','Meat/Poultry'],
['7','Produce'], ['8','Seafood']
];
var stCategory = new Ext.data.SimpleStore({
fields: ['value', 'text'],
data: dtCategory
});
var cbCategory = new Ext.form.ComboBox({
id: "cbCategory",
store: stCategory,
displayField: "text",
valueField: "value",
typeAhead: true,
mode: "local",
triggerAction: "all",
emptyText: "請選擇商品種類...",
editable: false,
allowBlank: false,
blankText: "商品種類必須選擇",
autoSelect: true,
selectOnFocus: true
});
cbCategory.setValue("all");
mode: "local" 表示資料已在記憶體中;若改為 remote,就要搭配 JsonStore 由伺服器分次提供。editable: false 讓使用者只能選不能打。triggerAction: "all" 則確保點下箭頭時顯示全部選項而非過濾後的結果。
var btnSearch = new Ext.Button({
id: 'btnSearch',
iconCls: 'btn_search',
text: '搜索',
handler: function(){
stProduct.load({
params: {
start: 0, limit: 10,
categoryName: Ext.getCmp("cbCategory").getValue(),
productName: Ext.getCmp("tfName").getValue()
}
});
}
});
var tb = new Ext.Toolbar({
id: 'tb',
items: ['商品種類:', cbCategory, '-', '商品名稱:', tfName, btnSearch, '->', btnHelp]
});
注意 '->' 這個特殊項目,它在 ExtJS 工具列中代表「推到最右側」,之後的元件都會靠右對齊。
var stProduct = new Ext.data.Store({
id: "st",
proxy: new Ext.data.HttpProxy({ url: "Default.aspx" }),
reader: new Ext.data.JsonReader({
totalProperty: "totalProperty",
root: "root",
fields: [
{name:"ProductID"}, {name:"ProductName"}, {name:"CategoryName"},
{name:"UnitPrice"}, {name:"Discontinued"}, {name:"QuantityPerUnit"},
{name:"CompanyName"}
]
})
});
stProduct.load({ params: { start: 0, limit: 10 } });
ProductID 刻意不寫進 ColumnModel,作為隱藏欄位存在——它不在畫面上顯示,但雙擊那一列時要用它組出請求網址,是典型的主鍵用法。
var cmProduct = new Ext.grid.ColumnModel([
new Ext.grid.RowNumberer(),
{ header:"產品名稱", dataIndex:"ProductName", sortable:true },
{ header:"產品種類", dataIndex:"CategoryName", sortable:true },
{ header:"單價", dataIndex:"UnitPrice", sortable:true },
{ header:"是否停產", dataIndex:"Discontinued", sortable:true },
{ header:"規格", dataIndex:"QuantityPerUnit", sortable:true },
{ header:"供貨商", dataIndex:"CompanyName", sortable:true }
]);
var grdProduct = new Ext.grid.GridPanel({
id: "grdProduct",
title: "商品信息",
cm: cmProduct,
store: stProduct,
selModel: new Ext.grid.RowSelectionModel({ single: true }),
height: screen.availHeight - 190,
bbar: pgtbProduct,
loadMask: true,
viewConfig: { forceFit: true }
});
RowNumberer() 自動產生序號欄;loadMask: true 在等待伺服器回應時顯示遮罩與轉圈提示,是必備的使用者回饋;forceFit: true 讓欄寬自動撐滿容器,不必手動計算像素。
表單用 layout: 'column' 搭配 columnWidth 做比例分割,每個區塊再套一層 layout: 'form':
new Ext.Panel({
columnWidth: .5, border: false, layout: 'form',
labelWidth: 60, labelAlign: 'right',
items: [{
xtype: 'textfield', id: 'ProductName', name: 'ProductName',
fieldLabel: '商品名稱', anchor: '95%'
}]
})
anchor: '95%' 讓欄寬隨容器縮放,是 ExtJS 響應式表單的標準手法。xtype 是元件的短名稱,寫 xtype: 'textfield' 比 new Ext.form.TextField({...}) 簡潔,效能也略好。
單選按鈕刻意拆成兩個獨立 Panel 各放一個 radio,並共用同一個 name: 'Discontinued'——這樣才能靠 column layout 讓「是」與「否」分列左右兩側,同時維持同組互斥的行為。
var tpProduct = new Ext.TabPanel({
id: 'tpProduct',
deferredRender: false, // 是否第一次顯示就渲染所有 tab
layoutOnTabChange: true,
activeTab: 0,
border: false,
items: [pnProduct, pnCategory]
});
這兩個屬性是一組。當一個大表單被拆進不同 tab,為了提交與載入方便,我們會在最外層包一個 FormPanel;但 deferredRender 預設為 true(未開啟的分頁不渲染),會導致表單抓不到那些尚未產生的欄位。把它設為 false 強制一次渲染全部,再搭配 layoutOnTabChange 讓切換時重新計算版面,問題就解決了。
grdProduct.on("rowdblclick", function(grid, rowIndex, e){
var row = grid.getStore().getAt(rowIndex).data;
fpProduct.form.load({
url: 'ProductInfo.aspx?type=getProductInfo&productId=' + row.ProductID,
waitMsg: '數據加載中...',
success: function(){
if (row.Discontinued == "是") {
Ext.getCmp('DiscontinuedOneID').setValue(true);
} else {
Ext.getCmp('DiscontinuedTwoID').setValue(true);
}
Ext.getCmp('CategoryImage').getEl().dom.src = "tempFile/" + row.CategoryName + ".png";
},
failure: function(){
Ext.Msg.alert("系統提示", "數據加載失敗!");
}
});
winProductInfo.show();
});
form.load() 會依欄位名稱自動對應 JSON 屬性並填入表單,所以後端回傳的欄位名稱必須和表單控制項的 name 完全一致,否則那格會是空的。單選按鈕與圖片不在表單欄位範圍內,因此要在 success 回呼裡手動設定。
buttons: [
{
text: '提交',
handler: function(){
if (fpProduct.getForm().isValid()) {
var record = grdProduct.getSelectionModel().getSelected();
fpProduct.getForm().submit({
method: 'post',
url: 'ProductInfo.aspx?type=updateProductInfo&productId=' + record.get("ProductID"),
waitMsg: '數據更新中...',
success: function(){
stProduct.reload();
Ext.Msg.alert("系統提示", "提交成功!");
},
failure: function(){ Ext.Msg.alert("系統提示", "提交失敗!"); }
});
}
}
},
{ text: '關閉', handler: function(){ winProductInfo.hide(); } }
]
getForm().isValid() 會跑一次全表單驗證,不通過就不送出;selectionModel().getSelected() 取回當前選取列的資料物件,用它取出隱藏的 ProductID 當作更新依據;提交成功後 store.reload() 重抓資料,畫面立刻反映最新狀態。
元件先定義、後組裝:所有元件都是獨立變數,最後才在 Viewport 裡組合。這樣每個元件都能單獨測試與替換。
隱藏欄位承載主鍵:不顯示在畫面上,卻是資料更新的關鍵,這是表格類後台的通用模式。
loadMask 與 waitMsg:任何需要等待伺服器的動作都該有視覺回饋,否則使用者會以為程式當機而反覆點擊。
這個寫法屬於 ExtJS 3.x 的 Ext.onReady 與 new Ext.Panel 時代。ExtJS 後續版本改採 MVVM/MVC 架構與 Ext.create(),授權也轉為商業模式。今天若要做類似後台,ExtJS 現代版、AG Grid 或 React 生態的表格方案都值得評估,但這份範例在「元件化思維」與「表單資料流」上的示範,放到任何框架都仍然適用。