Refreshing gridx cell value using DateTextBox - javascript

Working with gridx. I've added a Diji/form/DateTextBox to one of the columns.
I am able to save back to the grid's JSON, but I am not managing to update what is displayed in the cell.
function deadlineDecorator(value) {
return '<div data-dojo-type="dijit/form/DateTextBox" data-dojo-props="constraints:{datePattern: \'dd/MM/yyyy\'}" data-dojo-attach-point="deadlineCal" required="true" />';
}
function <portlet:namespace/>deadlineCellValueSet(gridData, storeData, cellWidget) {
cellWidget.deadlineCal.set('value', newDate(gridData));
cellWidget.deadlineCal.constraints.min = new Date();
}
var locale = dojo.require("dojo.date.locale");
function getDate(d){
res = locale.format(d, {
selector: 'date',
datePattern: 'dd/MM/yyyy'
});
return res;
}
function deadlineChange(cellWidget, cell) {
return [
[cellWidget.deadlineCal, 'onChange', function(e){
cell.setRawData(getDate(cellWidget.deadlineCal.value));
}]
];
}
I am creating the grid using this:
data = [{"id": 1, "dead": 18/12/2014}];
function creategrid() {
var gridData = {data: data};
var dataStore = new dojo.store.Memory(gridData);
grid.setStore(datastore);
};
How can I save the chosen date back to the JSON AND show that change in the cell.
I guess I could refresh the whole grid, but that doesn't seem like a very elegant solution?

Related

Angular Multiplying a Row of a Table

In my code, I have a table and the user can add a new empty row, to the table. I've put a multiply button next to every row. I want the user to be able to click this button and when a dialog opens and he says multiply, I want a copy of that row with the same information to be added to the table. I don't have a clue on how to perform this task. Here is my code, how can I manage this?
HTML of the copy-dialog component:
<button mat-stroked-button class="amber-fg mr-12" (click)="multiply()">Multiply</button>
TS:
multiply(){
}
TS of the table component:
addNewWorkItem() { //adds a new, empty row
let item: IWorkItem = {};
item.WorkItemStateType = this.workItemStates[0];
item.Product = {};
let tempData = this.dataSource.data.splice(0);
tempData.unshift(item);
this.dataSource = new MatTableDataSource(tempData);
this.EditIndex = 0;
this.products = [];
}
openCopyDialog(prm) {
const dialogRef = this._dialog.open(CopyDialogComponent, {
width: "700px",
data: prm,
});
dialogRef.afterClosed().subscribe((result) => {
//console.log(result);
});
}

jexcel table SUM column after change

I want to sum a column in jexcel after entering a value
This code is not working I don't know why:
var change = function(instance, cell, value) {
var cellName = $(instance).jexcel('getColumnNameFromId',$(cell).prop('id'));
$('#log').append('New change on cell'+ cellName+'to:'+ value + '<br>');
var thisid = $(cell).prop('id');
var splitted = thisid.split("-");
var nextcellid = ++splitted[1];
var nextcell = '0-'+nextcellid;
console.log(nextcell,'nextcell');
$("td#"+nextcell).html('<span>total</span>');
}
using onafterchange event:
$('#my').jexcel({
data:data,
colHeaders: ['Model'],
colWidths: [ 300 ],
onafterchange:function(instance){
console.log(instance)
},
columns: [
{ type: 'text' },
]
});
full handing events ready this url
https://bossanova.uk/jexcel/docs/events
or using this example
https://bossanova.uk/jexcel/examples/including-formulas-on-your-spreadsheet
To be honest, you can just use =SUM(A1:A10) in the column you would like to have the total. Pretty much like excel.

Strange javascript array push behaviour

I wrote a simple code to manipulate a query result to a bidimensional array (matrix) for a google chart datatable.
I'm getting nut on this strange array.push behaviour: when I push a new row in the matrix this method add the row, but also change the value of all the previus rows!
this is the code:
<script src="https://www.gstatic.com/charts/loader.js" type="text/javascript"></script>
<script type="text/javascript">
query is the matrix from the query
var qry = [[{label:'Montly', type: 'string'}, {label:'Model', type: 'string'}, {label:'total', type: 'number'}], ['12-2017','California T',parseFloat(13+13)], ['12-2017','458 Speciale',parseFloat(3+2)], ['12-2017','GTC4Lusso',parseFloat(2+6)], ['12-2017','458 Spider',parseFloat(0+1)], ['12-2017','GTC4Lusso T',parseFloat(2+0)], ['12-2017','California',parseFloat(0+2)], ['12-2017','488 Spider',parseFloat(16+7)], ['12-2017','FF',parseFloat(1+3)], ['12-2017','488 GTB',parseFloat(17+10)], ['12-2017','F12berlinetta',parseFloat(3+4)], ['12-2017','458 Italia',parseFloat(0+3)], ['12-2017','F12tdf',parseFloat(1+21)], ['12-2017','LaFerrari Aperta',parseFloat(0+1)], ['12-2017','812 Superfast',parseFloat(2+3)], ['12-2017','Portofino',parseFloat(1+1)], ['11-2017','458 Spider',parseFloat(2+4)], ['11-2017','GTC4Lusso',parseFloat(4+34)], ['11-2017','California T',parseFloat(8+15)], ['11-2017','488 GTB',parseFloat(9+12)], ['11-2017','LaFerrari',parseFloat(0+1)], ['11-2017','458 Speciale',parseFloat(2+2)], ['11-2017','GTC4Lusso T',parseFloat(0+1)], ['11-2017','FF',parseFloat(1+4)], ['11-2017','812 Superfast',parseFloat(3+1)], ['11-2017','California',parseFloat(0+3)], ['11-2017','488 Spider',parseFloat(11+8)], ['11-2017','458 Italia',parseFloat(1+5)], ['11-2017','F12tdf',parseFloat(0+1)], ['11-2017','Portofino',parseFloat(0+1)], ['11-2017','F12berlinetta',parseFloat(3+4)], ['10-2017','458 Italia',parseFloat(0+4)], ['10-2017','California T',parseFloat(9+18)], ['10-2017','California',parseFloat(0+8)], ['10-2017','812 Superfast',parseFloat(1+2)], ['10-2017','F12tdf',parseFloat(1+2)], ['10-2017','Portofino',parseFloat(2+0)], ['10-2017','488 GTB',parseFloat(8+14)], ['10-2017','FF',parseFloat(0+3)], ['10-2017','458 Spider',parseFloat(1+3)], ['10-2017','LaFerrari Aperta',parseFloat(0+1)], ['10-2017','F12berlinetta',parseFloat(5+8)], ['10-2017','458 Speciale',parseFloat(3+2)], ['10-2017','488 Spider',parseFloat(9+7)], ['10-2017','GTC4Lusso',parseFloat(2+4)], ['9-2017','California',parseFloat(0+4)], ['9-2017','458 Speciale Aperta',parseFloat(1+0)], ['9-2017','FF',parseFloat(3+6)], ['9-2017','812 Superfast',parseFloat(2+1)], ['9-2017','458 Italia',parseFloat(1+3)], ['9-2017','GTC4Lusso',parseFloat(2+6)], ['9-2017','F12tdf',parseFloat(1+0)], ['9-2017','LaFerrari',parseFloat(0+1)], ['9-2017','488 GTB',parseFloat(18+13)], ['9-2017','458 Spider',parseFloat(3+2)], ['9-2017','F12berlinetta',parseFloat(4+10)], ['9-2017','458 Speciale',parseFloat(5+1)], ['9-2017','California T',parseFloat(23+37)], ['9-2017','488 Spider',parseFloat(11+14)], ['8-2017','FF',parseFloat(0+1)], ['8-2017','458 Spider',parseFloat(0+1)], ['8-2017','F12berlinetta',parseFloat(0+3)], ['8-2017','GTC4Lusso',parseFloat(0+6)], ['8-2017','488 GTB',parseFloat(0+1)], ['8-2017','California T',parseFloat(0+2)], ['8-2017','458 Italia',parseFloat(0+2)], ['8-2017','California',parseFloat(0+2)], ['7-2017','488 GTB',parseFloat(9+14)], ['7-2017','458 Speciale',parseFloat(1+4)], ['7-2017','California T',parseFloat(14+20)], ['7-2017','GTC4Lusso',parseFloat(1+7)], ['7-2017','California',parseFloat(1+6)], ['7-2017','458 Italia',parseFloat(1+4)], ['7-2017','458 Speciale Aperta',parseFloat(1+0)], ['7-2017','F12berlinetta',parseFloat(3+7)], ['7-2017','FF',parseFloat(2+3)], ['7-2017','458 Spider',parseFloat(1+3)], ['7-2017','488 Spider',parseFloat(10+10)], ['7-2017','F12tdf',parseFloat(0+1)], ['6-2017','488 GTB',parseFloat(7+23)], ['6-2017','458 Italia',parseFloat(2+2)], ['6-2017','812 Superfast',parseFloat(1+0)], ['6-2017','FF',parseFloat(0+3)], ['6-2017','GTC4Lusso',parseFloat(2+16)], ['6-2017','458 Spider',parseFloat(3+6)], ['6-2017','F12tdf',parseFloat(0+2)], ['6-2017','LaFerrari',parseFloat(0+1)], ['6-2017','F12berlinetta',parseFloat(4+9)], ['6-2017','458 Speciale',parseFloat(2+3)], ['6-2017','California T',parseFloat(16+18)], ['6-2017','488 Spider',parseFloat(11+14)], ['5-2017','458 Speciale',parseFloat(4+4)], ['5-2017','458 Italia',parseFloat(0+2)], ['5-2017','F12berlinetta',parseFloat(2+5)], ['5-2017','F12tdf',parseFloat(0+3)], ['5-2017','FF',parseFloat(0+1)], ['5-2017','488 GTB',parseFloat(8+13)], ['5-2017','458 Spider',parseFloat(0+2)], ['5-2017','GTC4Lusso',parseFloat(0+6)], ['5-2017','488 Spider',parseFloat(6+12)], ['5-2017','California T',parseFloat(12+19)], ];
I want to extract the unique models from the column and create the series for the line chart
function extractColumn(arr, column) {
function reduction(previousValue, currentValue) {
previousValue.push(currentValue[column]);
return previousValue;
}
return arr.reduce(reduction, []);
}
var prima = extractColumn(qry,1);
var models = [...new Set(prima)];
with extract column I get all the values of the column 1,and with the spread operator I get the models array, without duplicate.
var testa = []; // the header of the matrix
var tabella = []; // the array for the DataTable
for (i=1; i<models.length; i++) {
riga[i]=0;
}
testa.push([{label:'Montly', type: 'string'}]);
for (i=1; i<models.length; i++) {
testa.push([{label:models[i], type:'number'}]);
} // this code create the header objects
tabella.push(testa); //push the header into the tabella array
console.log(tabella[0]); //this push is ok!
var mese=qry[1][0]; // first date value
var riga = []; // array to add as row of the matrix
riga[0]=mese; // start populating the firs row
the following code should create a new row and append it to the chart table.
It checks the date of every row of the query matrix (qry): if it's a new date append the created row to the chart table and start a new row, if not it goes on creating the new row.
for (i=1; i<qry.length; i++){ // iterate qry array
if (mese!=qry[i][0]) { // check if the date is new
console.log(riga); // all the created row are ok!
tabella.push(riga); // append the row to the array
console.table(tabella); // WEIRD PROBLEM: ALL THE ARRAY ROW ARE CHANGED
mese=qry[i][0]; // EVERY CICLE!
for (x=1; x<models.length; x++) {
riga[x]=0;
}
riga[0]=mese; //reset the new row array and set the date
} else {
for (t=0;t<models.length;t++){
pos = models.indexOf(qry[i][1]);
if (pos != -1) {
riga[pos]=qry[i][2]
}
} // this code populates the new row.
}
}
The following code create the chart
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(tabella);
var options = {
title: 'Montly Trend Focus on Complaint Type',
colors: ['#D9D904','#2A55FF','#000000'],
backgroundColor: {fill:'#FAFAFA',strokeWidth:1},
chartArea: {width:1800,height:380,left:70},
curveType: 'none',
legend: { position: 'bottom' },
hAxis: {direction:-1},
annotations: {
alwaysOutside: true,
textStyle: {
fontSize: 12,
bold: true,
color: '#000000',
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
}
this is an image from my console:
I solved my problem redeclareing the new row in the loop:
for (i=1; i<qry.length; i++){
if (mese!=qry[i][0]) {
tabella.push(riga);
var riga=[]; // NEW DECLARATION
mese=qry[i][0];
for (x=1; x<models.length; x++) {
riga[x]=0;
}
riga[0]=mese;
}
else {
for (t=0;t<models.length;t++){
pos = models.indexOf(qry[i][1]);
if (pos != -1){riga[pos]=qry[i][2]}
}
}
}
Hope this will be usefull for others.

SyntaxError: missing ) after formal parameters when adding if/else

Can anyone tell me what i am doing wrong , i want to have different views for different users in handsontable.I am defining the table as
document.addEventListener("DOMContentLoaded", function() {
var create_table = document.getElementById('create_table');
var mydata = document.getElementById('mydata').innerHTML;//to get the hidden element
var logged_user = document.getElementById('logged_user').innerHTML;// to get remote user
var plan_creator = document.getElementById('plan_creator').innerHTML;//to get the person who has created the plan
console.log(logged_user + " " + plan_creator);
console.log(mydata);
var searchResultCount=0;
var hot,searchFiled,resultCount;
function searchResultCounter(instance, row, col, value, result) {
Handsontable.plugins.Search.DEFAULT_CALLBACK.apply(this, arguments);
if (result) {
searchResultCount++;
}
}
var buttons = {
save:document.getElementById('save'),
load:document.getElementById('load'),
file:document.getElementById('file_export')
}
var objectData = JSON.parse(mydata);//to decode data in JSON format
console.log(objectData);
hot = new Handsontable(create_table, {
data:objectData,
colHeaders: true,
rowHeaders: true,
contextMenu: true,
minRows: 30,
minCols: 13,
maxCols:18,
maxRows:100,
copyPaste:true,
dropdownMenu: true,//plugin to display menu on column header
filters:true,
columnSorting:true,//plugin to enable sorting
sortIndicator:true,//to display sorting is done
comments:true,//to add comments
colHeaders:["Testcase Name","Cell Name","Customer","Flops","Title","Status","Mfix CCR","Scenerio Brief Description","Expected Results","CCR Status","CCR No","Remarks","Testcase Path"],
if(logged_user == plan_creator) {
columns:[//when using this not able to remove column
{data:'tc_name'},
{data:'cell_name'},
{data:'customer_name'},
{data:'flops' ,type:'numeric'},
{data:'title'},
{data:'status'},
{data:'mfix_ccr'},
{data:'test_scenerio'},
{data:'expected_results'},
{data:'ccr_status'},
{data:'ccr_num'},
{data:'remarks'},
{data:'tc_path'}],
}
else{
columns:[//when using this not able to remove column
{data:'tc_name' ,readOnly:true } ,
{data:'cell_name',readOnly:true },
{data:'customer_name',readOnly:true },
{data:'flops' ,type:'numeric',readOnly:true },
{data:'title',readOnly:true },
{data:'status',readOnly:true },
{data:'mfix_ccr',readOnly:true },
{data:'test_scenerio',readOnly:true },
{data:'expected_results',readOnly:true },
{data:'ccr_status',readOnly:true },
{data:'ccr_num',readOnly:true },
{data:'remarks'},//only remarks can be added by other user
{data:'tc_path',readOnly:true }],
}
search: {
callbak:searchResultCounter
}
});
searchFiled = document.getElementById('search_filed');
resultCount=document.getElementById('resultCount');
var exportPlugin=hot.getPlugin('exportFile');
Handsontable.dom.addEvent(searchFiled, 'keyup', function(event) {
var queryResult;
console.log(this.value);
searchResultCount = 0;
queryResult = hot.search.query(this.value);
console.log(queryResult);
//resultCount.innerText = searchResultCount.toString();
hot.render();
});
buttons.file.addEventListener('click', function() {// enabling the plugin to download the file
exportPlugin.downloadFile('csv', {filename: 'MyFile',columnHeaders:true});
});
I don't get any error when i remove the if/else statement and use only one scenerio .when using above code i am getting the error, but when i remove the if/else part and just use columns attribute in a simple way , i don't get this error.But i want to have different views for the creator of plan and others.
Is there any other way to do this?
Thanks
You can't use if statements when constructing an object, but you can use the ternary ?: operator, like this:
colHeaders: ... ,
columns: logged_user == plan_creator
? /* value in case they are equal */
: /* value in case they are not equal */,
search: ...
instead of using if else like
if(logged_user == plan_creator) {
columns:[//when using this not able to remove column
{data:'tc_name'},
{data:'cell_name'},
{data:'customer_name'},
{data:'flops' ,type:'numeric'},
{data:'title'},
{data:'status'},
{data:'mfix_ccr'},
{data:'test_scenerio'},
{data:'expected_results'},
{data:'ccr_status'},
{data:'ccr_num'},
{data:'remarks'},
{data:'tc_path'}],
}
else {}
you could use the ternary Operator:
columns: (logged_user === plan_creator)
? [//when using this not able to remove column
{data:'tc_name'},
...
]
: [//when using this not able to remove column
{data:'tc_name' ,readOnly:true },
...
]

Datatables: Export Excel Formatting

I'm having some issues when trying to format data when exporting to Excel using datatables. One of my columns contain a decimal point and displays OK when viewed in the browser as a table. When I export the table to excel this is rounding up the number in that column, this I do not want to happen. e.g shown in table '220419.07109' and when exported '220419.0711' I would prefer if this was just a string to maintain the full number.
function formatDataForExport(data, row, column, node) {
var string = data.toString();
return string;
}
function drawDatatable(JSONData) {
var dataSet = [];
table = $("#div").DataTable({
data: dataSet,
columns: columns(),
columnDefs: [{
"targets": columnTargets(showConcludedColumns),
"visible": false,
"searchable": false
}],
info: false,
searching: false,
paging: false,
ordering: false,
autoWidth: true,
responsive: true,
buttons: [{
extend: 'excel',
text: "Export to Excel",
exportOptions: {
columns: ":visible",
format: {
body: formatDataForExport
}
}
}]
});
}
You could use the following solution.
// Get the max value of an attribute of elements' list
var getMaxValue = function(elements, attr) {
var values = elements.map(function(){
return this.getAttribute(attr) || -Infinity;
}).toArray();
return Math.max.apply(Math, values);
}
$('#example').DataTable( {
dom: 'Bfrtip',
columns: [
{ data: 'Number' },
],
buttons: [
{
extend: 'excelHtml5',
customize: function(xlsx) {
//Get the built-in styles
//refer buttons.html5.js "xl/styles.xml" for the XML structure
var styles = xlsx.xl['styles.xml'];
//Create a custom number format
//Get the available id for the custom number format
var numFmtId = getMaxValue($('numFmts numFmt', styles), 'numFmtId') + 1
//XML Node: Custom number format for the timestamp column
var nFmt = '<numFmt numFmtId="' + numFmtId + '" formatCode="0.######################"/>';
// Add new node
el = $('numFmts', styles);
el.append(nFmt).attr('count', parseInt(el.attr('count'))+1);
//Create our own style to use the custom number format above
//XML Node: Custom style for the timestamp column
var style = '<xf numFmtId="' + numFmtId + '" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>';
// Add new node
el = $('cellXfs', styles);
el.append(style).attr('count', parseInt(el.attr('count'))+1);
// Index of our new style
var styleIdx = $('xf', el).length - 1;
//Apply new style to the first (A) column
var sheet = xlsx.xl.worksheets['sheet1.xml'];
//Set new style default for the column (optional)
$('col:eq(0)', sheet).attr('style', styleIdx);
//Apply new style to the existing rows of the first column ('A'), skipping header row
$('row:gt(0) c[r^="A"]', sheet).attr('s', styleIdx);
},
},
]
} );
Working JSFiddle
You could use different kinds of formatting there:
0.###################### - will show as many digits after decimal point as you have "#";
#.###################### - the same as above, but with no 0 in a number like 0.1234;
0.?????????????????????? - the same as above, but aligned by the decimal point
Simplified version, the resulted file opens correctly in Excel, but the shortcuts could affect other XLSX files reading software: JSFiddle

Categories

Resources