Added support for custom "single" button to gui tables

This commit is contained in:
Adolfo Gómez 2013-12-14 02:37:11 +00:00
parent 53258f2d7b
commit e925a2a356
4 changed files with 318 additions and 259 deletions

View File

@ -64,19 +64,19 @@ class DeployedServices(ModelHandler):
def item_as_dict(self, item): def item_as_dict(self, item):
val = { 'id': item.id, val = { 'id': item.id,
'name': item.name, 'name': item.name,
'comments': item.comments, 'comments': item.comments,
'state' : item.state, 'state' : item.state,
'service': Services.serviceToDict(item.service), 'service_id': item.service_id,
'initial_srvs' : item.initial_srvs, 'initial_srvs' : item.initial_srvs,
'cache_l1_srvs' : item.cache_l1_srvs, 'cache_l1_srvs' : item.cache_l1_srvs,
'cache_l2_srvs' : item.cache_l2_srvs, 'cache_l2_srvs' : item.cache_l2_srvs,
'max_srvs' : item.max_srvs, 'max_srvs' : item.max_srvs,
'user_services_count': item.userServices.count(), 'user_services_count': item.userServices.count(),
} }
if item.osmanager is not None: if item.osmanager is not None:
val['osmanager'] = OsManagers.osmToDict(item.osmanager) val['osmanager_id'] = item.osmanager.id
return val return val

View File

@ -12,10 +12,27 @@ gui.deployedservices.link = function(event) {
})); }));
gui.setLinksEvents(); gui.setLinksEvents();
var testClick = function(val, value, btn, tbl, refreshFnc) {
gui.doLog(value);
};
var counter = 0;
var testSelect = function(val, value, btn, tbl, refreshFnc) {
if( !val ) {
$(btn).removeClass('btn3d-info').addClass('disabled');
return;
}
$(btn).removeClass('disabled').addClass('btn3d-info');
counter = counter + 1;
gui.doLog('Select', counter.toString(), val, value);
};
var tableId = gui.deployedservices.table({ var tableId = gui.deployedservices.table({
container : 'deployed-services-placeholder', container : 'deployed-services-placeholder',
rowSelect : 'single', rowSelect : 'single',
buttons : [ 'new', 'edit', 'delete', 'xls' ], buttons : [ 'new', 'edit', 'delete', { text: gettext('Test'), css: 'disabled', click: testClick, select: testSelect }, 'xls' ],
onData: function(data) {
gui.doLog(data);
}
}); });
}); });

View File

@ -45,10 +45,12 @@ GuiElement.prototype = {
// Options: dictionary // Options: dictionary
// container: container ID of parent for the table. If undefined, table will be appended to workspace // container: container ID of parent for the table. If undefined, table will be appended to workspace
// buttons: array of visible buttons (strings), valid are [ 'new', 'edit', 'refresh', 'delete', 'xls' ], // buttons: array of visible buttons (strings), valid are [ 'new', 'edit', 'refresh', 'delete', 'xls' ],
// Can contain also objects with {'text': ..., 'fnc': ...}
// rowSelect: type of allowed row selection, valid values are 'single' and 'multi' // rowSelect: type of allowed row selection, valid values are 'single' and 'multi'
// scrollToTable: if True, will scroll page to show table // scrollToTable: if True, will scroll page to show table
// deferedRender: if True, datatable will be created with "bDeferRender": true, that will improve a lot creation of huge tables // deferedRender: if True, datatable will be created with "bDeferRender": true, that will improve a lot creation of huge tables
// //
// onData: Event (function). If defined, will be invoked on data load (to allow preprocess of data)
// onLoad: Event (function). If defined, will be invoked when table is fully loaded. // onLoad: Event (function). If defined, will be invoked when table is fully loaded.
// Receives 1 parameter, that is the gui element (GuiElement) used to render table // Receives 1 parameter, that is the gui element (GuiElement) used to render table
// onRowSelect: Event (function). If defined, will be invoked when a row of table is selected // onRowSelect: Event (function). If defined, will be invoked when a row of table is selected
@ -206,275 +208,311 @@ GuiElement.prototype = {
})).appendTo('head'); })).appendTo('head');
self.rest.overview(function(data) { // Gets "overview" data for table (table contents, but resume form) self.rest.overview(function(data) { // Gets "overview" data for table (table contents, but resume form)
var table = gui.table(title, tableId); if( options.onData ) {
if (options.container === undefined) { options.onData(data);
gui.appendToWorkspace('<div class="row"><div class="col-lg-12">' + table.text + '</div></div>'); }
} else {
$('#' + options.container).empty(); var table = gui.table(title, tableId);
$('#' + options.container).append(table.text); if (options.container === undefined) {
} gui.appendToWorkspace('<div class="row"><div class="col-lg-12">' + table.text + '</div></div>');
} else {
$('#' + options.container).empty();
$('#' + options.container).append(table.text);
}
// What execute on refresh button push // What execute on refresh button push
var onRefresh = options.onRefresh || function(){}; var onRefresh = options.onRefresh || function(){};
var refreshFnc = function() { var refreshFnc = function() {
// Refreshes table content // Refreshes table content
var tbl = $('#' + tableId).dataTable(); var tbl = $('#' + tableId).dataTable();
// Clears selection first // Clears selection first
TableTools.fnGetInstance(tableId).fnSelectNone(); TableTools.fnGetInstance(tableId).fnSelectNone();
//if( data.length > 1000 ) //if( data.length > 1000 )
gui.tools.blockUI(); gui.tools.blockUI();
self.rest.overview(function(data) { // Restore overview
setTimeout( function() {
tbl.fnClearTable();
tbl.fnAddData(data);
onRefresh(self);
gui.tools.unblockUI();
}, 0);
}); // End restore overview
return false; // This may be used on button or href, better disable execution of it
};
var btns = [];
if (options.buttons) {
// Generic click handler generator for this table
var clickHandlerFor = function(handler, action, newHandler) {
var handleFnc = handler || function(val, action, tbl) {gui.doLog('Default handler called for ', action);};
return function(btn) {
var tbl = $('#' + tableId).dataTable();
var val = this.fnGetSelectedData()[0];
setTimeout(function() {
if( newHandler ) {
handleFnc(action, tbl, refreshFnc);
} else {
handleFnc(val, action, tbl, refreshFnc);
}
}, 0);
};
};
var onCheck = options.onCheck || function(){ return true; }; // Default oncheck always returns true
// methods for buttons on row select
var editSelected = function(btn, obj, node) {
var sel = this.fnGetSelectedData();
var enable = sel.length == 1 ? onCheck("edit", sel) : false;
self.rest.overview(function(data) { // Restore overview if ( enable) {
setTimeout( function() { $(btn).removeClass('disabled').addClass('btn3d-success');
tbl.fnClearTable(); } else {
tbl.fnAddData(data); $(btn).removeClass('btn3d-success').addClass('disabled');
onRefresh(self); }
gui.tools.unblockUI(); };
}, 0); var deleteSelected = function(btn, obj, node) {
}); // End restore overview var sel = this.fnGetSelectedData();
return false; // This may be used on button or href, better disable execution of it var enable = sel.length == 1 ? onCheck("delete", sel) : false;
if (enable) {
$(btn).removeClass('disabled').addClass('btn3d-warning');
} else {
$(btn).removeClass('btn3d-warning').addClass('disabled');
}
}; };
var btns = []; $.each(options.buttons, function(index, value) { // Iterate through button definition
var btn = null;
if (options.buttons) { switch (value) {
// Generic click handler generator for this table case 'new':
var clickHandlerFor = function(handler, action, newHandler) { if(Object.keys(self.types).length !== 0) {
var handleFnc = handler || function(val, action, tbl) {gui.doLog('Default handler called for ', action);}; var menuId = gui.genRamdonId('dd-');
return function(btn) { var ordered = [];
var tbl = $('#' + tableId).dataTable(); $.each(self.types, function(k, v){
var val = this.fnGetSelectedData()[0]; ordered.push({
setTimeout(function() { type: k,
if( newHandler ) { css: v.css,
handleFnc(action, tbl, refreshFnc); name: v.name,
} else { description: v.description,
handleFnc(val, action, tbl, refreshFnc); });
} });
}, 0);
}; ordered = ordered.sort(function(a,b){return a.name.localeCompare(b.name);});
};
var onCheck = options.onCheck || function(){ return true; }; // Default oncheck always returns true btn = {
"sExtends" : "div",
// methods for buttons on row select "sButtonText" : api.templates.evaluate('tmpl_comp_dropdown', {
var editSelected = function(btn, obj, node) { label: gui.config.dataTableButtons['new'].text,
var sel = this.fnGetSelectedData(); css: gui.config.dataTableButtons['new'].css,
var enable = sel.length == 1 ? onCheck("edit", sel) : false; id: menuId,
tableId: tableId,
if ( enable) { columns: columns,
$(btn).removeClass('disabled').addClass('btn3d-success'); menu: ordered,
}),
};
} else { } else {
$(btn).removeClass('btn3d-success').addClass('disabled'); btn = {
} "sExtends" : "text",
}; "sButtonText" : gui.config.dataTableButtons['new'].text,
var deleteSelected = function(btn, obj, node) { "sButtonClass" : gui.config.dataTableButtons['new'].css,
var sel = this.fnGetSelectedData(); "fnClick" : clickHandlerFor(options.onNew, 'new', true),
var enable = sel.length == 1 ? onCheck("delete", sel) : false;
if (enable) {
$(btn).removeClass('disabled').addClass('btn3d-warning');
} else {
$(btn).removeClass('btn3d-warning').addClass('disabled');
}
};
$.each(options.buttons, function(index, value) { // Iterate through button definition
var btn;
switch (value) {
case 'new':
if(Object.keys(self.types).length !== 0) {
var menuId = gui.genRamdonId('dd-');
var ordered = [];
$.each(self.types, function(k, v){
ordered.push({
type: k,
css: v.css,
name: v.name,
description: v.description,
});
});
ordered = ordered.sort(function(a,b){return a.name.localeCompare(b.name);});
btn = {
"sExtends" : "div",
"sButtonText" : api.templates.evaluate('tmpl_comp_dropdown', {
label: gui.config.dataTableButtons['new'].text,
css: gui.config.dataTableButtons['new'].css,
id: menuId,
tableId: tableId,
columns: columns,
menu: ordered,
}),
}; };
}
} else { break;
btn = { case 'edit':
"sExtends" : "text", btn = {
"sButtonText" : gui.config.dataTableButtons['new'].text, "sExtends" : "text",
"sButtonClass" : gui.config.dataTableButtons['new'].css, "sButtonText" : gui.config.dataTableButtons.edit.text,
"fnClick" : clickHandlerFor(options.onNew, 'new', true), "fnSelect" : editSelected,
}; "fnClick" : clickHandlerFor(options.onEdit, 'edit'),
} "sButtonClass" : gui.config.dataTableButtons.edit.css,
break; };
case 'edit': break;
btn = { case 'delete':
"sExtends" : "text", btn = {
"sButtonText" : gui.config.dataTableButtons.edit.text, "sExtends" : "text",
"fnSelect" : editSelected, "sButtonText" : gui.config.dataTableButtons['delete'].text,
"fnClick" : clickHandlerFor(options.onEdit, 'edit'), "fnSelect" : deleteSelected,
"sButtonClass" : gui.config.dataTableButtons.edit.css, "fnClick" : clickHandlerFor(options.onDelete, 'delete'),
}; "sButtonClass" : gui.config.dataTableButtons['delete'].css,
break; };
case 'delete': break;
btn = { case 'refresh':
"sExtends" : "text", btn = {
"sButtonText" : gui.config.dataTableButtons['delete'].text, "sExtends" : "text",
"fnSelect" : deleteSelected, "sButtonText" : gui.config.dataTableButtons.refresh.text,
"fnClick" : clickHandlerFor(options.onDelete, 'delete'), "fnClick" : refreshFnc,
"sButtonClass" : gui.config.dataTableButtons['delete'].css, "sButtonClass" : gui.config.dataTableButtons.refresh.css,
}; };
break; break;
case 'refresh': case 'xls':
btn = { btn = {
"sExtends" : "text", "sExtends" : "text",
"sButtonText" : gui.config.dataTableButtons.refresh.text, "sButtonText" : gui.config.dataTableButtons.xls.text,
"fnClick" : refreshFnc, "fnClick" : function() { // Export to excel
"sButtonClass" : gui.config.dataTableButtons.refresh.css, api.templates.get('spreadsheet', function(tmpl) {
}; var styles = { 'bold': 's21', };
break;
case 'xls': var headings = [], rows = [];
btn = { $.each(columns, function(index, heading){
"sExtends" : "text", if( heading.bVisible === false ) {
"sButtonText" : gui.config.dataTableButtons.xls.text, return;
"fnClick" : function() { // Export to excel }
api.templates.get('spreadsheet', function(tmpl) { headings.push(api.spreadsheet.cell(heading.sTitle, 'String', styles.bold));
var styles = { 'bold': 's21', }; });
rows.push(api.spreadsheet.row(headings));
var headings = [], rows = []; $.each(data, function(index1, row) {
$.each(columns, function(index, heading){ var cells = [];
if( heading.bVisible === false ) { $.each(columns, function(index2, col){
if( col.bVisible === false ) {
return; return;
} }
headings.push(api.spreadsheet.cell(heading.sTitle, 'String', styles.bold)); var type = col.sType == 'numeric' ? 'Number':'String';
cells.push(api.spreadsheet.cell(row[col.mData], type));
}); });
rows.push(api.spreadsheet.row(headings)); rows.push(api.spreadsheet.row(cells));
$.each(data, function(index1, row) {
var cells = [];
$.each(columns, function(index2, col){
if( col.bVisible === false ) {
return;
}
var type = col.sType == 'numeric' ? 'Number':'String';
cells.push(api.spreadsheet.cell(row[col.mData], type));
});
rows.push(api.spreadsheet.row(cells));
});
var ctx = {
creation_date: (new Date()).toISOString(),
worksheet: title,
columns_count: headings.length,
rows_count: rows.length,
rows: rows.join('\n')
};
gui.doLog(ctx);
setTimeout( function() {
saveAs(new Blob([api.templates.evaluate(tmpl, ctx)],
{type: 'application/vnd.ms-excel'} ), title + '.xls');
}, 20);
}); });
}, // End export to excell var ctx = {
"sButtonClass" : gui.config.dataTableButtons.xls.css, creation_date: (new Date()).toISOString(),
worksheet: title,
columns_count: headings.length,
rows_count: rows.length,
rows: rows.join('\n')
};
gui.doLog(ctx);
setTimeout( function() {
saveAs(new Blob([api.templates.evaluate(tmpl, ctx)],
{type: 'application/vnd.ms-excel'} ), title + '.xls');
}, 20);
});
}, // End export to excell
"sButtonClass" : gui.config.dataTableButtons.xls.css,
};
break;
default: // Custom button, this has to be
try {
var css = (value.css ? value.css + ' ' : '') + gui.config.dataTableButtons.custom.css;
btn = {
"sExtends" : "text",
"sButtonText" : value.text,
"sButtonClass" : css,
}; };
if( value.click ) {
btn.fnClick = function(btn) {
var tbl = $('#' + tableId).dataTable();
var val = this.fnGetSelectedData()[0];
setTimeout(function() {
value.click(val, value, btn, tbl, refreshFnc);
}, 0);
};
}
if( value.select ){
btn.fnSelect = function(btn) {
var tbl = $('#' + tableId).dataTable();
var val = this.fnGetSelectedData()[0];
setTimeout(function() {
value.select(val, value, btn, tbl, refreshFnc);
}, 0);
};
}
} catch (e) {
gui.doLog('Button', value, e);
} }
}
if(btn) { if(btn) {
btns.push(btn); btns.push(btn);
} }
}); // End buttoon iteration }); // End buttoon iteration
} }
// Initializes oTableTools // Initializes oTableTools
var oTableTools = { var oTableTools = {
"aButtons" : btns, "aButtons" : btns,
"sRowSelect": options.rowSelect || 'none', "sRowSelect": options.rowSelect || 'none',
};
if (options.onRowSelect) {
var rowSelectedFnc = options.onRowSelect;
oTableTools.fnRowSelected = function() {
rowSelectedFnc(this.fnGetSelectedData(), $('#' + tableId).dataTable(), self);
}; };
}
if (options.onRowSelect) { if (options.onRowDeselect) {
var rowSelectedFnc = options.onRowSelect; var rowDeselectedFnc = options.onRowDeselect;
oTableTools.fnRowSelected = function() { oTableTools.fnRowDeselected = function() {
rowSelectedFnc(this.fnGetSelectedData(), $('#' + tableId).dataTable(), self); rowDeselectedFnc(this.fnGetSelectedData(), $('#' + tableId).dataTable(), self);
};
}
if (options.onRowDeselect) {
var rowDeselectedFnc = options.onRowDeselect;
oTableTools.fnRowDeselected = function() {
rowDeselectedFnc(this.fnGetSelectedData(), $('#' + tableId).dataTable(), self);
};
}
var dataTableOptions = {
"aaData" : data,
"aoColumns" : columns,
"oLanguage" : gui.config.dataTablesLanguage,
"oTableTools" : oTableTools,
// First is upper row,
// second row is lower
// (pagination) row
"sDom" : "<'row'<'col-xs-8'T><'col-xs-4'f>r>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
"bDeferRender": options.deferedRender || false,
}; };
}
var dataTableOptions = {
"aaData" : data,
"aoColumns" : columns,
"oLanguage" : gui.config.dataTablesLanguage,
"oTableTools" : oTableTools,
// First is upper row,
// second row is lower
// (pagination) row
"sDom" : "<'row'<'col-xs-8'T><'col-xs-4'f>r>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
"bDeferRender": options.deferedRender || false,
};
// If row is "styled" // If row is "styled"
if( row_style.field ) { if( row_style.field ) {
var field = row_style.field; var field = row_style.field;
var dct = row_style.dict; var dct = row_style.dict;
var prefix = row_style.prefix; var prefix = row_style.prefix;
dataTableOptions["fnCreatedRow"] = function( nRow, aData, iDataIndex ) { dataTableOptions.fnCreatedRow = function( nRow, aData, iDataIndex ) {
var v = dct !== undefined ? dct[this.fnGetData(iDataIndex)[field]] : this.fnGetData(iDataIndex)[field]; var v = dct !== undefined ? dct[this.fnGetData(iDataIndex)[field]] : this.fnGetData(iDataIndex)[field];
$(nRow).addClass(prefix + v); $(nRow).addClass(prefix + v);
gui.doLog(prefix + v); gui.doLog(prefix + v);
}; };
} }
$('#' + tableId).dataTable(dataTableOptions); $('#' + tableId).dataTable(dataTableOptions);
// Fix 3dbuttons // Fix 3dbuttons
gui.tools.fix3dButtons('#' + tableId + '_wrapper .btn-group-3d'); gui.tools.fix3dButtons('#' + tableId + '_wrapper .btn-group-3d');
// Fix form // Fix form
$('#' + tableId + '_filter input').addClass('form-control'); $('#' + tableId + '_filter input').addClass('form-control');
// Add refresh action to panel // Add refresh action to panel
$(table.refreshSelector).click(refreshFnc); $(table.refreshSelector).click(refreshFnc);
// Add tooltips to "new" buttons // Add tooltips to "new" buttons
$('#' + table.panelId + ' [data-toggle="tooltip"]').tooltip({ $('#' + table.panelId + ' [data-toggle="tooltip"]').tooltip({
container:'body', container:'body',
delay: { show: 1000, hide: 100}, delay: { show: 1000, hide: 100},
placement: 'auto right', placement: 'auto right',
});
// And the handler of the new "dropdown" button links
if( options.onNew ) { // If onNew, set the handlers for dropdown
$('#' + table.panelId + ' [data-type]').on('click', function(event){
event.preventDefault();
var tbl = $('#' + tableId).dataTable();
// Executes "onNew" outside click event
var type = $(this).attr('data-type');
setTimeout(function() {
options.onNew(type, tbl, refreshFnc);
}, 0);
}); });
// And the handler of the new "dropdown" button links }
if( options.onNew ) { // If onNew, set the handlers for dropdown
$('#' + table.panelId + ' [data-type]').on('click', function(event){ if (options.scrollToTable === true ) {
event.preventDefault(); var tableTop = $('#' + tableId).offset().top;
var tbl = $('#' + tableId).dataTable(); $('html, body').scrollTop(tableTop);
// Executes "onNew" outside click event }
var type = $(this).attr('data-type'); // if table rendered event
setTimeout(function() { if( options.onLoad ) {
options.onNew(type, tbl, refreshFnc); options.onLoad(self);
}, 0); }
}); }); // End Overview data
} }); // End Tableinfo data
if (options.scrollToTable === true ) {
var tableTop = $('#' + tableId).offset().top;
$('html, body').scrollTop(tableTop);
}
// if table rendered event
if( options.onLoad ) {
options.onLoad(self);
}
}); // End Overview data
}); // End Tableinfo data
return '#' + tableId; return '#' + tableId;
}, },

View File

@ -49,6 +49,10 @@
text: '<span class="fa fa-save"></span> <span class="label-tbl-button">' + gettext('Xls') + '</span>', text: '<span class="fa fa-save"></span> <span class="label-tbl-button">' + gettext('Xls') + '</span>',
css: 'btn btn3d-info btn3d btn3d-tables', css: 'btn btn3d-info btn3d btn3d-tables',
}, },
'custom': {
text: null,
css: 'btn btn3d-default btn3d btn3d-tables',
},
}; };
gui.genRamdonId = function(prefix) { gui.genRamdonId = function(prefix) {