drawCallback issue
drawCallback issue
Hi everyone,
I'm trying to create a new column, calculated from the differences between consecutives weights.
DATE | WEIGHT | DIFFERENCE
12/10/17 | 70 | 5
12/06/17 | 65 | -2
11/03/17 | 67 | 0
...
New column is: DIFFERENCE
First, I define a new column, initialized to 0, like this
{ "data": null, "defaultContent": 0 }
and no "render" function, since I want to populate it dynamically via drawCallback, like this:
"drawCallback": function (settings) {
var api = this.api();
var myData = api.rows({ page: 'current' }).data();
for (var i = 1; i < myData.length; i++) {
var d = parseFloat((myData[i].weight - myData[i-1].weight) * -1);
}
},
So, I get a weight difference per index (i), stored in 'd', except last row (there's not previous value, it must be 0).
The question is, how can I assign 'd' values for each cell of column DIFFERENCE?
Thanks in advance!
This question has an accepted answers - jump to answer
Answers
That's a slightly tricky one! I can't think of a much more efficient way to do it (it feels like there should be).
To write to a cell value use:
where
columnIndex
is the column index you want to update - 2 in this case I think.This works by using the
i
loop counter as a row selector for the currently visible rows.Allan
Ok, Allan, that works!
Actually, I noticed two things (please correct me if I'm wrong):
1) I have to supply an initial value to 'd' inside the loop (an arbitrary value, like 0 or 'n/a') (this is trivial, doesn't affect the behaviour of drawCallback).
2) To use 'drawCallback', it seems to be necessary to process a column with a real data source, as I see it doesn't work with 'data:null' and 'defaultContent:0' (like in my former example). To test it, I have used a non-visible field at the moment, but my intention is to create a new field in the table that stores the weight differences (and then process it as my convenience).
Thank you for your quick response!
Jose
Hi Jose,
1) Yes. Otherwise it might be undefined - good thinking.
2) You could try using
cell().render()
to get the data that is shown in the cell, regardless of if it was from the defaultContent or something else.Allan
Indeed Allan, using cell().render(), I get the data shown in the cell:
api.cell( ':eq('+i+')', 2, { page: 'current' } ).render( 'display' )
where 2 is columnIndex. But it still doesn't allow me set the new values (weight differences) on rendered column. Passing column index (of a rendered column) to cell().data() doesn't work, since cell().data() doesn't recognize that kind of columns (at least, I think so).
It seems the best option here is cell().data(), iterating over a column with real data.
Regards,
Jose