Ext JS 的 GridPanel 內建拖放(Drag & Drop)支援,只要設定 ddGroup 與 enableDragDrop,再搭配 DropTarget 自訂放下的行為,就能做到兩個表格之間搬移資料列的效果。以下示範單行拖曳。
// 第一個 GRID
var firstGrid = new Ext.grid.GridPanel({
ddGroup : 'secondGridDdGroup', // 對應第二個 GRID 的 ddGroup
store : firstGridStore,
enableDragDrop : true, // 啟動 GridPanel 中被選取列的拖動行為
// 其他屬性省略
});
// 第二個 GRID
var secondGrid = new Ext.grid.GridPanel({
ddGroup : 'firstGridDdGroup', // 對應第一個 GRID 的 ddGroup
store : secondGridStore,
enableDragDrop : true,
// 其他屬性省略
});
這裡的設計有點巧妙:每個 Grid 的 ddGroup 指向對方的群組名稱,讓拖放來源與目標能配對上。
var firstGridDropTargetEl = firstGrid.getView().el.dom.childNodes[0].childNodes[1];
var firstGridDropTarget = new Ext.dd.DropTarget(firstGridDropTargetEl, {
ddGroup : 'firstGridDdGroup', // 與第二個 GRID 的 ddGroup 相同
copy : true,
notifyDrop : function(ddSource, e, data){
function addRow(record, index, allItems) {
var foundItem = secondGridStore.find('name', record.data.name);
if (foundItem == -1) {
firstGridStore.add(record);
firstGridStore.sort('name', 'ASC');
ddSource.grid.store.remove(record);
}
}
Ext.each(ddSource.dragData.selections, addRow);
return true;
}
});
var secondGridDropTargetEl = secondGrid.getView().el.dom.childNodes[0].childNodes[1];
var secondGridDropTarget = new Ext.dd.DropTarget(secondGridDropTargetEl, {
ddGroup : 'secondGridDdGroup', // 與第一個 GRID 的 ddGroup 相同
copy : true,
notifyDrop : function(ddSource, e, data){
function addRow(record, index, allItems) {
var foundItem = secondGridStore.find('name', record.data.name);
if (foundItem == -1) {
secondGridStore.add(record);
secondGridStore.sort('name', 'ASC');
ddSource.grid.store.remove(record);
}
}
Ext.each(ddSource.dragData.selections, addRow);
return true;
}
});
notifyDrop 是放下時真正執行的處理器。裡面的 addRow 做了三件事:用 store.find('name', ...) 檢查目標表格中是否已有同名資料以避免重複;有的話什麼都不做;沒有的話加入目標 store、依名稱排序,最後從來源 store 移除該筆。這樣一來資料就完成了「搬移」而非「複製」。
Ext.each(ddSource.dragData.selections, addRow) 表示一次放下的可以是多筆選取資料,逐一處理。
getView().el.dom.childNodes[0].childNodes[1] 這種寫法直接依賴 DOM 的節點位置,Ext JS 版本一升級、DOM 結構一變就會失效。較穩妥的做法是用 class 選擇器或 Grid 提供的 API 取得 drop target 元素。foundItem 查的是 secondGridStore,但搬移方向是往第二個 Grid,查錯 store 會導致去重失效,實作時要對照方向確認。copy: true 代表拖曳時按住某鍵才複製;若你要的是「一定搬移」,這個設定要一併調整。store.sync() 或自行送出 Ajax,把變更存回伺服器。