在 Ext JS 的 Grid 中取用資料,可以從兩個方向著手:整個 Store 的全部列,或使用者目前選取的列。以下把實務上最常用到的幾種寫法整理在一起。
grid.getStore().getRange(0, store.getCount()); // 得到 grid 所有的列
getRange 回傳 Record 陣列,起訖索引不含結尾。
grid.getSelectionModel().getSelections(); // 得到選取的所有列
注意:若未宣告类似 var sm = new Ext.grid.CheckboxSelectionModel(); 的多選模型,呼叫這句會發生「沒有該物件或屬性」的錯誤。也就是說,多選能力必須先在 selectionModel 上設定好,getSelections() 才有意義。
取得選取列後,可用 get 搭配欄位的 dataIndex 取出該欄的值:
var selectRows = grid.getSelectionModel().getSelections();
selectRows[0].get("某欄的 dataIndex 屬性值"); // 取選取列記錄的該欄值
grid.selModel.selections.items; // 得到選取的所有列
這是直接存取內部集合,較不受 API 版本包裝影響,但也較不穩定,正式程式碼中優先使用 getSelections()。
grid.getSelectionModel().getSelected(); // 得到選取列的第一列
rowclick 事件會帶入 rowIndex,可用它從 Store 取出對應的 Record,再直接餵給表單:
proLevelGrid.on('rowclick', function (proLevelGrid, rowIndex, event) {
var record = proLevelGrid.getStore().getAt(rowIndex);
addProductLevel_form.getForm().loadRecord(record);
alert(record.get('id'));
});
loadRecord 是 Ext JS 相當方便的功能,能依表單欄位的 name 自動對應 Record 的欄位並填入,省下手動逐欄指派的麻煩。
var grid1_RowClick = function (a, b, c) {
// 取得特定欄的資料
var id = a.getStore().getAt(b).get("Id");
};