在 ExtJS 應用開發中,實現兩個 GridPanel 之間的行拖拽移動是常見需求。本文提供一個完整的單行拖拽範例,展示如何透過 ddGroup 與 DropTarget 實現跨 Grid 的資料互傳,並防止重複資料新增。
ddGroup 必須對應目標 Grid 的 ddGroup,才能建立連結。notifyDrop 事件以完成資料搬移邏輯。var firstGrid = new Ext.grid.GridPanel({
ddGroup: 'secondGridDdGroup', // 對應第二個 Grid 的 ddGroup
store: firstGridStore,
enableDragDrop: true, // 啟用行拖曳
// ... 其他屬性省略
});
var secondGrid = new Ext.grid.GridPanel({
ddGroup: 'firstGridDdGroup', // 對應第一個 Grid 的 ddGroup
store: secondGridStore,
enableDragDrop: true,
// ... 其他屬性省略
});
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) {
// 檢查目標 Store 是否已存在相同 name 的記錄
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;
}
});
ddGroup 交叉設定,形成雙向拖拽通道。store.find() 檢查 name 欄位,避免重複資料寫入。sort() 維持排序,並從來源 Store 移除記錄。notifyDrop 手動控制移除時機。BufferedRenderer 或 Locking 功能,getView().el.dom.childNodes[0].childNodes[1] 的索引可能不同,需依實際 DOM 結構調整。copy: true 改用移動模式,或於 notifyDrop 回傳 false 取消預設行為,自行處理批次更新。Ext.grid.plugin.DragDrop 外掛,API 更簡潔。透過 ddGroup 配對與 DropTarget 事件處理,即可輕鬆實現 Grid 間的行級拖拽互傳。本範例展示了去重、排序、雙向同步的完整流程,可直接套用於實際專案中。