ABGridPanel.js
/* file has been through JSLint as of 1.14.2011 Changes to js should go through JSLint
http://www.jslint.com/
click the 'The Good Parts'
Predefined = 'Ext, window, directEventFailure' (without the ticks) */
/***********************************************************************************************
Extension of Ext.net.GridPanel to standardize grid rendering and functionality
***********************************************************************************************/
// config required for extension
Ext.net.ABGridPanel = function (config) {
Ext.net.ABGridPanel.superclass.constructor.call(this, config);
};
// -------------------------------------------------------------------------------------------
// Gets the entire dom code for the page.
// -------------------------------------------------------------------------------------------
DomHtml = function () {
strDomHtml = document.body.innerHTML;
//''Remove unwanted characters that cause IIS to suspect sql injection.
var arrRemoveChars = ['
', '
'];
for (var i = 0; i < arrRemoveChars.length; i++) {
strDomHtml = strDomHtml.replace(new RegExp(arrRemoveChars[i], "g"), "");
}
return encodeURI(strDomHtml);
};
// extension of the grid - defines new name and what to extend
Ext.extend(Ext.net.ABGridPanel, Ext.net.GridPanel, {
// -------------------------------------------------------------------------------------------
// List of new properties added to the grid
// -------------------------------------------------------------------------------------------
allowExportToExcel: false,
allowExportToPDF: false,
userSettings: '',
saveSettings: true,
allowGroup: true,
sessionName: '',
selectModel: 'Row',
reconfigSettings: '',
removedColumns: [],
initColumnModelConfig: [],
allowEditReferenceNumber: false,
saveEditToUpdate: false,
sessionSelected: '',
selectedId: '',
byPassFlagAtReLoadForSortHandler: true,
byPassFlagAtReLoadForResizeHandler: true,
// -------------------------------------------------------------------------------------------
// Initialize the grid with default settings
// -------------------------------------------------------------------------------------------
initComponent: function () {
var defConfig = {
stripeRows: true,
loadMask: { showMask: true },
saveMask: { showMask: true }
};
// apply default config
Ext.apply(this, defConfig);
// call parent initComponent applying the config changes
Ext.net.ABGridPanel.superclass.initComponent.call(this);
// add No Data, expand/collapse, reset and export functionality to the toolbar
this.setDefaultToolbar();
// if Reconfig Settings have been set on init alter the grid column model
if (!Ext.isEmpty(this.reconfigSettings)) {
this.setReconfig();
}
// If there are user defined settings then restructure grid
this.setDefaultConfigSettings(false);
// add default listeners
this.setDefaultListeners();
},
/************************************************/
/**** Start public call functions ****/
/**** functions are used outside of js file ****/
/************************************************/
// -------------------------------------------------------------------------------------------
// Sets the record count label based on the store count
// -------------------------------------------------------------------------------------------
setRecordCount: function (excludeWarning) {
var d = ' ',
exclude = excludeWarning || false,
ct = this.store.getCount(),
tbID = this.id + '_lblRecordCount',
tbID2 = this.id + '_lblNoRecords';
if (ct === 0 && exclude === false) {
d = String.format(localeLang.noDataFoundText, ct);
}
this.topToolbar.items.get(tbID2).setText(d, false);
d = String.format(localeLang.recordsCountText, ct);
this.topToolbar.items.get(tbID).setText(d);
if (ct > 999) {
Ext.Msg.alert(localeLang.maxReachedTitleText, localeLang.maxReachedText);
}
}, // end setRecordCount
// -------------------------------------------------------------------------------------------
// Sets the export buttons to enabled or disabled based on the record count
// -------------------------------------------------------------------------------------------
setExportButtons: function (excludeWarning) {
if (this.topToolbar.items.length > 0) {
var exclude = excludeWarning || false;
this.setRecordCount(exclude);
var ct = this.store.getCount();
if (this.allowExportToExcel === true) {
this.topToolbar.items.get(this.id + '_tbExcelDOM').setDisabled(ct === 0);
}
if (this.allowExportToPDF === true) {
this.topToolbar.items.get(this.id + '_tbPDFDOM').setDisabled(ct === 0);
}
} // end toolbar.items.length > 0
}, // end setExportButtons
// -------------------------------------------------------------------------------------------
// Get the selected id that will be saved to session
// -------------------------------------------------------------------------------------------
getSelectedId: function () {
if (this.getSelectionModel().hasSelection()) {
this.selectedId = this.getSelectionModel().selections.items[0].id;
}
},
// -------------------------------------------------------------------------------------------
// Formats the group header based on whether or not we need to change the record displaying
// This was required because if we grouped by ids it would display id instead of meaningful text
// -------------------------------------------------------------------------------------------
getGroupHeader: function (group) {
var cm = this.getColumnModel(),
display = cm.getColumnById(this.view.getGroupField()).recordDisplay,
header;
if (display === undefined) {
return group.text;
} else {
header = group.text.split(':');
return header[0] + ': ' + group.rs[0].get(display);
}
},
// -------------------------------------------------------------------------------------------
// Gets the group header height for the multi line header
// -------------------------------------------------------------------------------------------
getGroupHeaderPluginHeight: function () {
var i, iCount = 0;
for (i = 0; i < this.plugins.length; i += 1) {
if (this.plugins[i].pluginType !== undefined && this.plugins[i].pluginType === 'groupHeader') {
iCount += 1;
}
}
// TODO: hard coded height - figure out how to calculate this is why the selectors header continue to grow
return (iCount * 22);
},
// -------------------------------------------------------------------------------------------
// Get the selected ids to array
// -------------------------------------------------------------------------------------------
getIDPropertyValues: function () {
var values = [];
Ext.each(this.store.getAllRange(), function (record) {
values.push(record.id);
});
return values;
},
/************************************************/
/**** End public call functions ****/
/************************************************/
/****** Private Functions ******/
/************************************************/
/**** Start Functions for default listeners ****/
/************************************************/
doBeforeCellEditHandler: function (e) {
switch (e.field) {
case "ReinsurerContractReferenceEdit":
case "ReinsurerClaimNumberEdit":
case "CedentContractNumber":
if ((e.record.data.AcctgParticipationID == 0 && e.record.data.ContractSectionID == 0) ||
(e.field == "ReinsurerClaimNumberEdit" && e.record.data.ClaimID == 0)) {
return false;
}
}
return true;
},
// -------------------------------------------------------------------------------------------
// Listener handler for the cell click - handler is set in ABGridPanel.vb
// -------------------------------------------------------------------------------------------
doCellClickHandler: function (item, rowIndex, columnIndex, e) {
if (columnIndex !== -1) {
var url = '', cm = this.getColumnModel();
if (!Ext.isEmpty(cm)) {
switch (cm.config[columnIndex].rendererFormat) {
case 'LinkEditReferenceContractNumber':
var rec = this.getStore().getAt(rowIndex),
editWindowID = rec.get(cm.config[columnIndex].url),
oWind = Ext.getCmp(editWindowID),
contractSectionID = rec.data.ContractSectionID || '';
if (!Ext.isEmpty(oWind)) {
url = oWind.autoLoadURL || '';
oWind.loadContent(String.format(url, 'ContractSectionID=' + contractSectionID + '&EditWindowID=' + editWindowID));
oWind.show();
}
break;
case 'LinkEditReferenceClaimNumber':
var rec = this.getStore().getAt(rowIndex),
editWindowID = rec.get(cm.config[columnIndex].url),
oWind = Ext.getCmp(editWindowID),
claimID = rec.data.ClaimID || '';
if (!Ext.isEmpty(oWind)) {
url = oWind.autoLoadURL || '';
oWind.loadContent(String.format(url, 'ClaimID=' + claimID + '&EditWindowID=' + editWindowID));
oWind.show();
}
break;
case 'LinkOpenWindow':
case 'LinkOpenWindowFormatValueAsDate':
case 'ImageLinkOpenWindow':
case 'LinkPopupOrDocument':
var rec = this.getStore().getAt(rowIndex),
editWindowID = rec.get(cm.config[columnIndex].url),
oWind = Ext.getCmp(editWindowID),
paramValue = rec.data.QueryParams || '';
if (rec.data.QueryParams) {
if (!Ext.isEmpty(oWind)) {
url = oWind.autoLoadURL || '';
oWind.loadContent(String.format(url, paramValue + '&EditWindowID=' + editWindowID));
oWind.show();
}
}
break;
case 'CellClickImage':
var imageID = this.getStore().getAt(rowIndex).get(cm.getDataIndex(columnIndex));
// uploads do not have callbacks for failure error
Ext.net.DirectMethods.OpenDocument(imageID, { isUpload: true });
case 'LinkShowValueNoUrl':
case 'Link':
case 'LinkPercent':
case 'LinkTwoDecimals':
case 'LinkNoDecimals':
case 'DocumentImageLink':
case 'ImageLink':
case 'DocumentLink':
case 'LinkMessage':
// If the grid has been given a name for session selected then add the listener to record it.
this.getSelectedId();
if (!Ext.isEmpty(this.selectedId)) {
Ext.net.DirectMethods.SaveSelectedGridID(this.selectedId, this.sessionSelected, {
failure: function (errorMsg) {
var m = !Ext.isEmpty(errorMsg) ? errorMsg.substring(0, 1000) : '';
directEventFailure('saveGridSettingsCellClick SaveGridSettings: ' + m);
}
});
}
break;
} // end switch
}
}
},
doColumnMoveHandler: function (oldIndex, newIndex) {
this.setToUnsavedView();
},
doColumnResizeHandler: function (columnIndex, newSize) {
this.setToUnsavedView();
},
doSortChangeHandler: function (item, sortInfo) {
if (this.byPassFlagAtReLoadForSortHandler) {
this.byPassFlagAtReLoadForSortHandler = false;
}
else {
this.setToUnsavedView();
}
},
doGroupChangeHandler: function (item, groupField) {
this.setToUnsavedView();
},
doHideHandler: function (item) {
this.setToUnsavedView();
},
setToUnsavedView: function () {
var caption = localeLang.unsavedViewText
, tbMenu = this.topToolbar.items.get(this.id + '_tbSetting')
, tbResetPreviousID = this.id + '_tbResetPrevious'
, itm = Ext.getCmp(tbResetPreviousID);
if (!Ext.isEmpty(tbMenu)) {
if (Ext.isEmpty(itm)) {
tbMenu.menu.add({ id: tbResetPreviousID, text: localeLang.settingsPreviousText, listeners: { click: { fn: function (el, e) { this.resetUserSettingsToPrevious(); }, scope: this}} })
}
// Update the text of the button
tbMenu.setText(caption, false);
}
},
// -------------------------------------------------------------------------------------------
// Sets the visibility of the expand/collapse toolbar buttons
// -------------------------------------------------------------------------------------------
setExpandCollapseVisibility: function () {
var isMultilevelGrid = this.isMultilevelGrid();
if (this.allowGroup === true || isMultilevelGrid) {
var bln = (this.store.groupField === undefined || this.store.groupField === false) && !isMultilevelGrid,
ct = this.store.getCount(),
tbID = this.id + '_tbExpand',
itm = this.topToolbar.items.get(tbID);
itm.setVisible(!bln);
itm.setDisabled(ct === 0);
tbID = this.id + '_tbCollapse';
itm = this.topToolbar.items.get(tbID);
itm.setVisible(!bln);
itm.setDisabled(ct === 0);
}
}, // end setExpandCollapse
isMultilevelGrid: function () {
for (var i = 0, len = this.plugins.length; i < len; i++) {
if (this.plugins[i].id == 'expander') {
return true;
}
}
return false;
},
getExpander: function () {
for (var i = 0, len = this.plugins.length; i < len; i++) {
if (this.plugins[i].id == 'expander') {
return this.plugins[i];
}
}
return null;
},
expandAll: function () {
var item = this.getExpander();
if (item != null && this.isGrouped() == false) {
item.expandAll();
}
else {
this.getView().expandAllGroups();
}
},
collapseAll: function () {
var item = this.getExpander();
if (item != null && this.isGrouped() == false) {
item.collapseAll();
}
else {
this.getView().collapseAllGroups();
}
},
isGrouped: function () {
var grp = true;
try
{
this.getView().getGroups()
}
catch (e)
{
grp = false;
}
return grp;
},
// -------------------------------------------------------------------------------------------
// Sets the focus and selects the row if the id had already been selected
// -------------------------------------------------------------------------------------------
setFocusAndSelectRow: function () {
if (this.selectedId) {
var idx = this.store.indexOfId(parseInt(this.selectedId, 10));
if (idx !== -1) {
var vw = this.getView(),
stCount = this.store.getCount();
this.getSelectionModel().selectRow(idx);
if (idx < stCount - 1) {
idx += 1;
}
// TODO: if it is grouping then idx is not row count but grouping + row count
vw.focusRow(idx);
vw.getRow(idx).scrollIntoView();
}
}
},
// -------------------------------------------------------------------------------------------
// Used on EditReferenceWindow - selects the first row and makes it editable
// -------------------------------------------------------------------------------------------
setSelectRowAndEdit: function () {
var idx = 0;
this.getSelectionModel().selectRow(idx);
this.startEditing(idx, 1);
},
// -------------------------------------------------------------------------------------------
// Starts editing in the grid - keep it here we need to only add
// -------------------------------------------------------------------------------------------
// startGridEdit: function () {
// if (e.getKey() === e.ENTER) {
// var record = this.getSelectionModel().getSelected(),
// index = this.store.indexOf(record);
// this.startEditing(index, 1);
// }
// },
/************************************************/
/**** End Functions for default listeners ****/
/***** --------------------------------- *****/
/***** Start Functions for Toolbar Buttons *****/
/************************************************/
// -------------------------------------------------------------------------------------------
// Exports the data based on the format type -
// NOTE: Upload Direct Methods do not retrun failure so can not add the standard function callback
// -------------------------------------------------------------------------------------------
exportData: function (exportType) {
showMask(localeLang.exportText);
var strDomHtml = '';
if (exportType == 'xlsDOM' || exportType == 'pdfDOM') {
strDomHtml = DomHtml();
}
Ext.net.DirectMethods.ExportData(exportType, '', strDomHtml, this.id, {
success: function () { Ext.net.Mask.hide(); },
failure: function (errorMsg) { var m = !Ext.isEmpty(errorMsg) ? errorMsg.substring(0, 1000) : ''; directEventFailure('exportData ExportData ' + m); }
});
},
// -------------------------------------------------------------------------------------------
// Resets the grid to the default settings
// -------------------------------------------------------------------------------------------
resetUserSettings: function () {
showMask(localeLang.resettingText);
dmResetGridSettings(this);
},
resetUserSettingsToPrevious: function () {
showMask(localeLang.resettingText);
dmResetToPreviousGridSettings(this);
},
// -------------------------------------------------------------------------------------------
// Saves the grid settings to db
// -------------------------------------------------------------------------------------------
saveUserSettings: function () {
showMask(localeLang.savingingText);
this.userSettings = Ext.encode(this.getCurrentGridFormat());
dmSaveGridSettings(this);
},
/************************************************/
/**** End Functions for Toolbar buttons ****/
/***** --------------------------------- *****/
/***** Start Functions for initComponent *****/
/************************************************/
// -------------------------------------------------------------------------------------------
// reconfigs the columns based on columns added to a Reconfig Collection in code behind
// -------------------------------------------------------------------------------------------
setReconfig: function (reconfigItems) {
var ar, i, z, index, len, width, col, dataI, rc, cm = this.getColumnModel();
if (reconfigItems) {
ar = reconfigItems;
} else {
ar = Ext.decode(this.reconfigSettings);
}
for (i = 0; i < ar.length; i += 1) {
index = cm.getIndexById(ar[i].columnID);
width = ar[i].width;
// don't use grid removeColumn/addColumn because it effects the store causing other issues
// actions are defined by: ABReconfigColumnCollection.vb
switch (ar[i].action) {
case 'remove':
// Will use this to add the column if it is a detail config
if (index !== -1) { // make sure it exists before trying to remove it
col = cm.getColumnAt(index);
if (ar[i].isInitChange === false) {
this.removedColumns.push({ columnID: ar[i].columnID, columnIndex: index, config: col });
}
cm.removeColumn(index);
}
break;
case 'add':
if (index === -1) {
rc = this.removedColumns;
for (z = 0, len = rc.length; z < len; z += 1) {
if (rc[z].columnID === ar[i].columnID) {
cm.addColumn(rc[z].config, rc[z].columnIndex);
// remove the added column
rc.splice(z, 1);
this.removedColumns = rc;
break;
}
}
}
break;
case 'resize':
if (index !== -1) {
cm.setColumnWidth(index, width, false);
}
break;
case 'tooltiptext':
if (index !== -1) {
cm.setColumnTooltip(index, ar[i].toolTipText);
}
break;
case 'changeheader':
if (index !== -1) {
cm.setColumnHeader(index, ar[i].toolTipText);
}
break;
case 'changerenderer':
if (index !== -1) {
col = cm.getColumnAt(index);
col.rendererFormat = ar[i].changeRenderer;
}
break;
case 'group':
if (index !== -1) {
dataI = cm.getDataIndex(index);
this.store.groupBy(dataI, false);
} else {
this.store.groupField = '';
}
break;
} // end switch
} // end for reconfigSettings
}, //end setReconfig
// -------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------
setSettingsMenu: function (bRevert) {
var caption = localeLang.customViewText
, tbMenu = this.topToolbar.items.get(this.id + '_tbSetting')
, tbResetID = this.id + '_tbResetDefault'
, tbResetPreviousID = this.id + '_tbResetPrevious'
, itm = Ext.getCmp(tbResetID)
, itmResetPrevious = Ext.getCmp(tbResetPreviousID);
if (!Ext.isEmpty(tbMenu)) {
if (Ext.isEmpty(itm)) {
caption = localeLang.customViewText;
// Add the Revert to Default to the menu if it isn't already there
tbMenu.menu.add({ id: tbResetID, text: localeLang.settingsDefaultText, listeners: { click: { fn: function (el, e) { this.resetUserSettings(); }, scope: this}} })
} else if (bRevert === true) {
caption = localeLang.defaultViewText;
// remove the Restore Default menu option
tbMenu.menu.remove(tbResetID);
}
if (!Ext.isEmpty(itmResetPrevious)) {
tbMenu.menu.remove(tbResetPreviousID);
}
// Update the text of the button
tbMenu.setText(caption, false);
}
},
setGridConfigModel: function (configSettings) {
var ar = configSettings;
// Set sort order
this.store.sort(ar.sortState.field, ar.sortState.direction);
// Set group by
this.store.groupBy(ar.groupField[0].dataIndex, false);
// columns {newIndex, oldIndex, header, dataIndex, width, hidden}
var cm = this.getColumnModel()
, colIndex
, moveToColIndex;
// If GroupBy Column is not hidden, turn off the grid setting hideGroupedColumn
if (ar.groupField[0].dataIndex != false) {
this.getView().hideGroupedColumn = ar.groupField[0].hidden
}
// Set the hidden and width of columns
Ext.each(ar.columns, function (col) {
// Find by dataindex because it may not still be at the same index
colIndex = cm.findColumnIndex(col.dataIndex);
if (colIndex !== -1) {
if (cm.isHidden(colIndex) !== col.hidden) {
// set hidden
cm.setHidden(colIndex, col.hidden);
}
if (cm.getColumnWidth(colIndex) !== col.width) {
// set width
cm.setColumnWidth(colIndex, col.width, false);
}
} // col != -1
});
// Move the column
Ext.each(ar.columns, function (col) {
moveToColIndex = col.newIndex;
// Find by dataindex because it may not still be at the same index
colIndex = cm.findColumnIndex(col.dataIndex);
if (colIndex !== -1) {
if (moveToColIndex !== colIndex) {
cm.moveColumn(colIndex, moveToColIndex);
}
}
});
},
// -------------------------------------------------------------------------------------------
// If there are user defined settings then restructure grid
// -------------------------------------------------------------------------------------------
setDefaultConfigSettings: function () {
var arTb, ar, i, r, itemType, cm, arCol, colIndex, moveToColIndex;
// Get the Initial Column Structure
if (this.saveSettings === true) {
this.initColumnModelConfig = this.getCurrentGridFormat();
}
if (this.userSettings) {
this.setSettingsMenu();
// reset the column model it init config
var ar = Ext.decode(this.userSettings);
this.setGridConfigModel(ar);
if (this.topToolbar) {
// top toolbar {index, value}
arTb = ar.topToolBar;
// make sure there are top toolbar items
if (this.topToolbar.items.length > 0) {
for (i = 0; i < arTb.length; i += 1) {
itemType = this.topToolbar.items.items[i].xtype;
if (itemType !== undefined) {
// capture only checkboxes, radios & combos
switch (itemType) {
case 'checkbox':
this.topToolbar.items.items[i].checked = arTb[i].value;
break;
case 'radio':
this.topToolbar.items.items[i].checked = arTb[i].value;
break;
case 'radiogroup':
r = arTb[i].value;
this.topToolbar.items.items[i].items[r].checked = true;
break;
case 'coolitetriggercombo':
this.topToolbar.items.items[i].value = arTb[i].value;
break;
} // end switch
} // end item xtype
} // end tb length loop
} // end test for toolbar items
} // end skip toolbar
}
}, // end
// -------------------------------------------------------------------------------------------
// Adds the required default listeners on the grid, view and store
// -------------------------------------------------------------------------------------------
setDefaultListeners: function () {
// adds a listener to the view refresh to alter the availability of the expand collapse button
this.view.addListener('Refresh', function (el) { this.setExpandCollapseVisibility(); }, this);
// adds a listener to the store load to alter the availability of the export buttons
// and to fix an issue where the bottom scrollbar disappears when a headerrow is added
this.store.addListener('Load', function (el) { this.setExportButtons(); try { this.syncSize(); } catch (e) { return false;} }, this);
// adds a listener if there is a previously selected id to set focus and select the row
this.addListener('ViewReady', function (el) { if (this.selectedId) { this.setFocusAndSelectRow(); } });
this.setEditListener();
}, // end setDefaultListeners
// -------------------------------------------------------------------------------------------
// Add listener for editing the grids
// -------------------------------------------------------------------------------------------
setEditListener: function () {
if (this.allowEditReferenceNumber === true) {
if (this.saveEditToUpdate === true) {
// adds a listener for the afteredit event
this.addListener('AfterEdit', saveUpdateGridEditReferenceNumbers);
} else {
this.addListener('AfterEdit', afterGridEditReferenceNumbers);
}
if (this.ForceValidation === true) {
this.addListener('ValidateEdit', saveUpdateGridEditReferenceNumbers);
}
// adds a listner to the key stroke to open the textbox editor
this.addListener('KeyDown', function (el) {
if (el.getKey() === el.ENTER) {
var record = this.getSelectionModel().getSelected(),
index = this.store.indexOf(record);
this.startEditing(index, 1);
}
});
}
},
// -------------------------------------------------------------------------------------------
// Add default buttons to the toolbar
// -------------------------------------------------------------------------------------------
setDefaultToolbar: function () {
var addExportSpacer = false;
// No Data Label - add the class so the label appears correctly formatted (can't override in main class because it changes all)
this.topToolbar.add(new Ext.form.Label({ id: this.id + '_lblNoRecords', reorderable: false, text: ' ', cls: 'x-grid3-label-value-no-data span' }));
// ToolbarFill - right aligns the export buttons
this.topToolbar.add('->');
if (this.saveSettings === true) {
this.topToolbar.addButton({ id: this.id + '_tbSetting', iconCls: "icon-cog", text: localeLang.defaultViewText, iconAlign: 'right'
, menu: {
xtype: "menu",
items: [{ text: localeLang.settingsSaveText, iconCls: "icon-disk", listeners: { click: { fn: function (el, e) { this.saveUserSettings(); }, scope: this}}}]
} // menu
}) // button1
// Toolbar spacer
this.topToolbar.add('-');
}
if (this.allowGroup === true || this.isMultilevelGrid()) {
// Expand Collapse buttons
this.topToolbar.addButton({ id: this.id + '_tbExpand', reorderable: false, iconCls: "icon-expand-all", tooltip: localeLang.expandText, disabled: true, listeners: { click: { fn: function (el, e) { this.expandAll(); }, scope: this}} });
this.topToolbar.addButton({ id: this.id + '_tbCollapse', reorderable: false, iconCls: "icon-collapse-all", tooltip: localeLang.collapseText, disabled: true, listeners: { click: { fn: function (el, e) { this.collapseAll(); }, scope: this}} });
// Toolbar spacer
this.topToolbar.add('-');
}
// Add the required export buttons
if (this.allowExportToExcel === true) {
this.topToolbar.addButton({ id: this.id + '_tbExcelDOM', reorderable: false, tooltip: localeLang.toExcelText, disabled: true, iconCls: 'icon-pageexcel', listeners: { click: { fn: function (el, e) { this.exportData('xlsDOM'); }, scope: this}} });
addExportSpacer = true;
}
if (this.allowExportToPDF === true) {
this.topToolbar.addButton({ id: this.id + '_tbPDFDOM', reorderable: false, tooltip: localeLang.toPdfText, disabled: true, iconCls: 'icon-pagewhiteacrobat', listeners: { click: { fn: function (el, e) { this.exportData('pdfDOM'); }, scope: this}} });
addExportSpacer = true;
}
if (addExportSpacer === true) {
// Toolbar spacer
this.topToolbar.add('-');
}
// Record Count Label - add the class so the label appears correctly formatted (can't override in main class because it changes all)
this.topToolbar.add(new Ext.form.Label({ id: this.id + '_lblRecordCount', reorderable: false, text: String.format(localeLang.recordsCountText, 0), cls: 'x-grid3-label-value span' }));
}, // end setDefaultToolbar
/************************************************/
/***** End Functions for initComponent *****/
/************************************************/
// -------------------------------------------------------------------------------------------
// Get the initial index of a colum by id - helper function
// -------------------------------------------------------------------------------------------
getInitIndexById: function (id) {
if (!Ext.isEmpty(this.initColumnModelConfig.columns)) {
// check the initial Column Model first for the original index
for (var i = 0, len = this.initColumnModelConfig.columns.length; i < len; i++) {
if (this.initColumnModelConfig.columns[i].id == id) { return i; }
}
}
// if there is no initial Column Model then use the grid column model
return this.getColumnModel().getIndexById(id);
},
// -------------------------------------------------------------------------------------------
// Revert the grid to it's initial settings
// -------------------------------------------------------------------------------------------
revertGrid: function () {
// reset the column model it init config
this.setGridConfigModel(this.initColumnModelConfig);
// reset the settings model
this.setSettingsMenu(true);
},
revertGridToPreviousSetting: function () {
if (this.userSettings.script === "") {
this.revertGrid();
this.setSettingsMenu(true);
}
else {
var ar = Ext.decode(this.userSettings);
this.setGridConfigModel(ar);
this.setSettingsMenu(false);
}
},
// -------------------------------------------------------------------------------------------
// Gets the format of the current grid for settings
// -------------------------------------------------------------------------------------------
getCurrentGridFormat: function () {
// define the object to hold the settings
var settings = {
sortState: {}, // {field, direction}
groupField: [], // {dataIndex, header, hidden}
topToolBar: [], // for check boxes and radio button settings in top toolbar to the LEFT of ToolBarFill {index, value}
columns: [] // {newIndex, oldIndex, header, dataIndex, width, hidden, dataType, dataTypeClass}
};
var groupFieldDataIndex;
// Sorting
settings.sortState = this.store.getSortState() || { field: '', direction: '' };
// Grouping
if (!Ext.isEmpty(this.store.groupField)) {
groupFieldDataIndex = this.store.groupField;
}
settings.groupField.push({ dataIndex: groupFieldDataIndex, header: '', hidden: this.getView().hideGroupedColumn });
// Top Toolbar - Only care about items up to No Data
var tbNoRecords = this.id + '_lblNoRecords';
var x = this.topToolbar.items.indexOfKey(tbNoRecords);
if (x > 0) {
for (var i = 0; i < x; i += 1) {
var itemType = this.topToolbar.items.items[i].xtype;
if (!Ext.isEmpty(itemType)) {
// capture only checkboxes, radios & combos
switch (itemType) {
case 'checkbox':
settings.topToolBar.push({ index: i, value: this.topToolbar.items.items[i].checked });
break;
default:
break;
} // end switch
} //end itemtype if
} // end for
} // end if
// current column structure
var cm = this.getColumnModel();
for (i = 0; i < cm.config.length; i += 1) {
var oldI = this.getInitIndexById(cm.config[i].id)
, di = cm.getDataIndex(i);
settings.columns.push({ newIndex: i
, oldIndex: oldI
, header: cm.getColumnHeader(i)
, dataIndex: di
, width: cm.getColumnWidth(i)
, hidden: groupFieldDataIndex == di ? this.getView().hideGroupedColumn : cm.isHidden(i)
});
}
return settings;
}, // end getCurrentGridFormat
onHeaderRowHiddenChange: function (cm, colIndex, hidden) {
if (this.view.mainHd) {
var display = hidden ? "none" : "",
rowIndex = 0;
for (rowIndex; rowIndex < this.view.headerRows.length; rowIndex++) {
var tr = this.view.mainHd.child("tr.x-grid3-hd-row-r" + rowIndex);
if (tr && tr.dom.cells.length > colIndex) {
Ext.fly(tr.dom.cells[colIndex]).dom.style.display = display;
}
}
this.syncHeaders.defer(100, this);
}
}
}); // end gridpanel
Ext.reg("abgridpanel", Ext.net.ABGridPanel);
ABGridPanel
Imports System.ComponentModel
Imports System.Web.UI
Imports System.Drawing
Imports System.Web
Imports Ext.Net
Imports System.Text
<Designer(GetType(EmptyDesigner))> _
<DefaultProperty("")> _
<Description("AB Grid Panel")> _
Public Class ABGridPanel
Inherits GridPanel
Private m_ToolbarDroppable As Ext.Net.ToolbarDroppable
Public Overrides ReadOnly Property XType() As String
Get
Return "abgridpanel"
End Get
End Property
Public Overrides ReadOnly Property InstanceOf() As String
Get
Return "Ext.net.ABGridPanel"
End Get
End Property
Public Overrides ReadOnly Property ConfigOptions() As ConfigOptionsCollection
Get
Dim cOpt As ConfigOptionsCollection = MyBase.ConfigOptions
With cOpt
.Add("reconfigSettings", "", Me.ReconfigSettings)
.Add("sessionName", "", Me.SessionName)
.Add("userSettings", "", Me.UserSettings)
.Add("allowGroup", True, Me.AllowGroup)
.Add("includeGroupSummary", True, Me.IncludeGroupSummary)
.Add("includeGridSummary", True, Me.IncludeGridSummary)
.Add("allowExportToExcel", False, Me.AllowExportToExcel)
.Add("allowExportToPDF", False, Me.AllowExportToPDF)
.Add("saveSettings", True, Me.SaveSettings)
.Add("allowEditReferenceNumber", False, Me.AllowEditReferenceNumber)
.Add("isSubGrid", False, Me.IsSubGrid)
.Add("saveEditToUpdate", False, Me.SaveEditToUpdate)
.Add("sessionSelected", "", Me.SessionSelected)
.Add("selectedId", "", Me.SelectedId)
.Add("forceValidation", False, Me.ForceValidation)
.Add("includePanelResizer", True, Me.IncludePanelResizer)
.Add("byPassFlagAtReLoadForSortHandler", True, True)
End With
Return cOpt
End Get
End Property
Public Sub New()
MyBase.New()
'// set the height in here instead of the js init config so that the height can be altered by setting the property
Me.Height = 350
End Sub
Protected Overrides Sub OnBeforeClientInit(ByVal sender As Observable)
MyBase.OnBeforeClientInit(sender)
' Register the Icons needed for export toolbar buttons
With ResourceManager
.RegisterIcon(Global.Ext.Net.Icon.PageWhiteAcrobat) 'PDF
.RegisterIcon(Global.Ext.Net.Icon.PageExcel) 'Excel
End With
'// Add listener for cell click - images and edit reference numbers will run code
Me.Listeners.CellClick.Handler = "item.doCellClickHandler(item, rowIndex, columnIndex, e);"
'// TODO: This should only be done when a grid is editable instead of for every grid. Consider a property on the grid
If Me.Listeners.BeforeEdit.Handler = String.Empty Then
Me.Listeners.BeforeEdit.Handler = "return this.doBeforeCellEditHandler(e);"
End If
If Me.SaveSettings = True Then
'//Listeners for various grid Edit events
Me.Listeners.ColumnMove.Handler = "this.doColumnMoveHandler(oldIndex, newIndex);"
Me.Listeners.ColumnResize.Handler = "this.doColumnResizeHandler(columnIndex,newSize);"
Me.Listeners.SortChange.Handler = "this.doSortChangeHandler(item,sortInfo);"
Me.Listeners.GroupChange.Handler = "this.doGroupChangeHandler(item,groupField);"
Me.Listeners.Hide.Handler = "this.doHideHandler(item);"
End If
End Sub
Protected Overloads Overrides Sub OnInit(ByVal e As EventArgs)
MyBase.OnInit(e)
'// Add plugin to maintain ScrollPosition
Me.Plugins.Add(New GridPanelMaintainScrollPositionOnRefresh)
'// Add plugin to wrap the headers when the column is too big
Me.Plugins.Add(New GridMultiLineHeader)
'// standard class for the grids
Me.Cls = "standardGrid"
If Me.IsSubGrid = False Then
'// Add plugin to for the panel resizer
If Me.IncludePanelResizer = True AndAlso Me.AutoHeight = False Then Me.Plugins.Add(New PanelResizer)
'// Changes the class to show the edit icons in the column header
If Me.AllowEditReferenceNumber = True Then Me.Cls = "editGrid"
'// Defaults the View to GroupView no matter what was previously selected
If Me.AllowGroup Then Me.ViewType = eViewType.GroupView
'// Allows Grouping
Select Case Me.ViewType
Case eViewType.GroupView
Me.View.Add(New GroupingView With {.SplitHandleWidth = "15", .HideGroupedColumn = True, .GroupTextTpl = "{[#{" & Me.ID & "}.getGroupHeader(values)]}"}) '//({[values.rs.length]} {[values.rs.length > 1 ? 'Records' : 'Record']})
Case eViewType.GridView
Me.View.Add(New GridView With {.SplitHandleWidth = "15"})
End Select
'// Adds the Subtotal Row for each group
If Me.IncludeGroupSummary = True Then Me.Plugins.Add(New GroupingSummary)
'// Adds the GrandTotal for Grid
If Me.IncludeGridSummary = True Then Me.Plugins.Add(New ABX.GridSummary)
'// Adds the select model for the grid
Select Case SelectModel
Case eSelectModel.none
Case eSelectModel.Row
Me.SelectionModel.Add(New RowSelectionModel With {.SingleSelect = True, .MoveEditorOnEnter = False})
Case eSelectModel.RowMultiSelect
Me.SelectionModel.Add(New RowSelectionModel)
Case eSelectModel.Checkbox
Me.SelectionModel.Add(New CheckboxSelectionModel With {.CheckOnly = True, .MoveEditorOnEnter = False})
Case eSelectModel.CheckboxSingleSelect
Me.SelectionModel.Add(New CheckboxSelectionModel With {.SingleSelect = True, .HideCheckAll = True, .CheckOnly = True})
End Select
'// Add a top toolbar if it's not already created in markup
If Me.TopBar.Count = 0 Then Me.TopBar.Add(New Toolbar)
Else
Me.AllowGroup = False
Me.AutoHeight = True
If Me.AllowEditReferenceNumber = True Then
Me.Cls = "editGrid"
Else
Me.Cls = "nested-grid"
Me.IncludeGridSummary = False
Me.AllowExportToExcel = False
Me.AllowExportToPDF = False
Me.IncludeGroupSummary = False
End If
End If
End Sub
Public Sub ResetGrid()
Me.AddScript(Me.ClientID & ".setExportButtons(true);")
End Sub
#Region "Public Properties"
'selectModel
<ConfigOption(), NotifyParentProperty(True), DefaultValue(eSelectModel.Row)> _
<Description("Session Name to save the settings too. Default = ''")> _
Public Property SelectModel() As eSelectModel
Get
Dim obj As Object = Me.ViewState("SelectModel")
Return If((obj Is Nothing), eSelectModel.Row, DirectCast(obj, eSelectModel))
End Get
Set(ByVal value As eSelectModel)
Me.ViewState("SelectModel") = value
End Set
End Property
'ViewType
<ConfigOption(), NotifyParentProperty(True), DefaultValue(eViewType.GridView)> _
<Description("Session Name to save the settings too. Default = ''")> _
Public Property ViewType() As eViewType
Get
Dim obj As Object = Me.ViewState("ViewType")
Return If((obj Is Nothing), eViewType.GridView, DirectCast(obj, eViewType))
End Get
Set(ByVal value As eViewType)
Me.ViewState("ViewType") = value
End Set
End Property
<ConfigOption(), DefaultValue(True)> _
<Description("")> _
Public Overridable Property IncludePanelResizer() As Boolean
Get
Dim obj = Me.ViewState("IncludePanelResizer")
Return If(obj Is Nothing, True, CBool(obj))
End Get
Set(ByVal value As Boolean)
Me.ViewState("IncludePanelResizer") = value
End Set
End Property
<ConfigOption(), DefaultValue(True)> _
<Description("Adds the Save Settings option to the toolbar")> _
Public Overridable Property SaveSettings() As Boolean
Get
Dim obj = Me.ViewState("SaveSettings")
Return If(obj Is Nothing, True, CBool(obj))
End Get
Set(ByVal value As Boolean)
Me.ViewState("SaveSettings") = value
End Set
End Property
<ConfigOption(), DefaultValue(False)> _
<Description("")> _
Public Overridable Property IsSubGrid() As Boolean
Get
Dim obj = Me.ViewState("IsSubGrid")
Return If(obj Is Nothing, False, CBool(obj))
End Get
Set(ByVal value As Boolean)
Me.ViewState("IsSubGrid") = value
End Set
End Property
<ConfigOption(), DefaultValue(False)> _
<Description("")> _
Public Overridable Property SaveEditToUpdate() As Boolean
Get
Dim obj = Me.ViewState("SaveEditToUpdate")
Return If(obj Is Nothing, False, CBool(obj))
End Get
Set(ByVal value As Boolean)
Me.ViewState("SaveEditToUpdate") = value
End Set
End Property
<ConfigOption(), DefaultValue(True)> _
<Description("Allow Edit of Reference #s")> _
Public Overridable Property AllowEditReferenceNumber() As Boolean
Get
Dim obj = Me.ViewState("AllowEditReferenceNumber")
Return If(obj Is Nothing, False, CBool(obj))
End Get
Set(ByVal value As Boolean)
Me.ViewState("AllowEditReferenceNumber") = value
End Set
End Property
<ConfigOption(), NotifyParentProperty(True), DefaultValue("")> _
<Description("(optional) Session Name to save the settings too. Default = ''")> _
Public Property ReconfigSettings() As String
Get
Return If(DirectCast(Me.ViewState("ReconfigSettings"), String), "")
End Get
Set(ByVal value As String)
Me.ViewState("ReconfigSettings") = value
End Set
End Property
<ConfigOption(), NotifyParentProperty(True), DefaultValue("")> _
<Description("")> _
Public Property SessionSelected() As String
Get
Return If(DirectCast(Me.ViewState("SessionSelected"), String), "")
End Get
Set(ByVal value As String)
Me.ViewState("SessionSelected") = value
End Set
End Property
<ConfigOption(), NotifyParentProperty(True), DefaultValue("")> _
<Description("")> _
Public Property SelectedId() As String
Get
Return If(DirectCast(Me.ViewState("SelectedId"), String), "")
End Get
Set(ByVal value As String)
Me.ViewState("SelectedId") = value
End Set
End Property
<ConfigOption(), NotifyParentProperty(True), DefaultValue("")> _
<Description("(optional) Session Name to save the settings too. Default = ''")> _
Public Property SessionName() As String
Get
Return If(DirectCast(Me.ViewState("SessionName"), String), "")
End Get
Set(ByVal value As String)
Me.ViewState("SessionName") = value
End Set
End Property
<ConfigOption(), NotifyParentProperty(True), DefaultValue("")> _
<Description("(optional) Hidden Field on Page that holds the grid settings. Used to send to session for grid reformat and for exporting. Default = ''")> _
Public Property UserSettings() As String
Get
Return If(DirectCast(Me.ViewState("UserSettings"), String), "")
End Get
Set(ByVal value As String)
Me.ViewState("UserSettings") = value
End Set
End Property
<ConfigOption(), DefaultValue(True)> _
<Description("Allow Grouping of records. Default = true")> _
Public Overridable Property AllowGroup() As Boolean
Get
Dim obj = Me.ViewState("AllowGroup")
Return If(obj Is Nothing, True, CBool(obj))
End Get
Set(ByVal value As Boolean)
Me.ViewState("AllowGroup") = value
If value = False Then
Me.IncludeGroupSummary = False
Me.IncludeGridSummary = False
End If
End Set
End Property
<ConfigOption(), DefaultValue(True)> _
<Description("Allow Grouping of records. Default = false")> _
Public Overridable Property IncludeGroupSummary() As Boolean
Get
Dim obj = Me.ViewState("IncludeGroupSummary")
Return If(obj Is Nothing, False, CBool(obj))
End Get
Set(ByVal value As Boolean)
Me.ViewState("IncludeGroupSummary") = value
End Set
End Property
<ConfigOption(), DefaultValue(True)> _
<Description("Allow Grouping of records. Default = false")> _
Public Overridable Property IncludeGridSummary() As Boolean
Get
Dim obj = Me.ViewState("IncludeGridSummary")
Return If(obj Is Nothing, False, CBool(obj))
End Get
Set(ByVal value As Boolean)
Me.ViewState("IncludeGridSummary") = value
End Set
End Property
<ConfigOption(), DefaultValue(False)> _
<Description("Allow Export to Excel Format. Default = true")> _
Public Property AllowExportToExcel() As Boolean
Get
Dim obj = Me.ViewState("AllowExportToExcel")
Return If(obj Is Nothing, False, CBool(obj))
End Get
Set(ByVal value As Boolean)
Me.ViewState("AllowExportToExcel") = value
End Set
End Property
<ConfigOption(), DefaultValue(False)> _
<Description("Allow Export to PDF Format. Default = true")> _
Public Property AllowExportToPDF() As Boolean
Get
Dim obj = Me.ViewState("AllowExportToPDF")
Return If(obj Is Nothing, False, CBool(obj))
End Get
Set(ByVal value As Boolean)
Me.ViewState("AllowExportToPDF") = value
End Set
End Property
#End Region
End Class