Tabulator: how to modify local array when deleting rows? - javascript

I'm trying to build an interactive table that could be modified by the user. In my case, the original dataset is a local array of objects.
Tabulator has the buttonCross option to delete rows, but it only affects the table visuals. How can I make it find the matching object the row presents and delete it from the tabledata array?
Here's the code I'm working with:
let tabledata = [{
animal: "hippo",
color: "grey"
},
{
animal: "puma",
color: "black"
},
{
animal: "flamingo",
color: "pink"
}
];
let table = new Tabulator("#example-table", {
data: tabledata,
layout: "fitDataFill",
addRowPos: "bottom",
reactiveData: true,
headerSort: false,
columns: [ //define the table columns
{
title: "animal",
field: "animal",
editor: "input"
},
{
title: "color",
field: "color",
editor: "input"
},
{
formatter: "buttonCross",
width: 40,
align: "center",
cellClick: function (e, cell) {
cell.getRow().delete();
}
},
],
});
Codepen here.
Would really appreciate some tips on how to make this work!

Working example for tabulator
the filter function is used to remove the current item for the collection
filter Filter API.
First filter the object you don't need and then assign it to tabledata.
cellClick: function (e, cell) {
debugger;
var animalToDelete={ animal:cell.getRow().getData().animal,
color:cell.getRow().getData().color
};
var filtered=tabledata.filter(function(x){
debugger;
return x.animal!=animalToDelete.animal
&& x.color!=animalToDelete.color;
});
tabledata=filtered;
cell.getRow().delete();
}

You could also look to use tabulator in Reactive Data Mode
In this mode it will update the table in real time to match the provided data array as it is changed, and vice versa it will update the array to match the table.
To do this set the reactiveData property to true in the tables constructor object.
//create table and assign data
var table = new Tabulator("#example-table", {
reactiveData:true, //enable reactive data
data:tableData, //assign data array
columns:[
{title:"Name", field:"name"},
{title:"Age", field:"age", align:"left", formatter:"progress"},
{title:"Favourite Color", field:"col"},
{title:"Date Of Birth", field:"dob", sorter:"date", align:"center"},
]
});
It will then maintain a link with the initial data source

Related

javascript get string text from json data

I'm creating a table in react using material UI and trying to figure out how to extract itemlocation from itemInfo and store it in a new column in the table. I know I can do it from the back end, but I can't, and all I want is to be able to extract the string from the item info. I provided an example of how the table and I'll put should look, as well as a snippet of sample code, and I hope this helps because this is how I was thinking of doing it, and I was hoping if anyone knew how I could do it without going into the backend.
simple code
const columns1 = [{
field: "itemInfo",
headerName: "itemInfo",
headeralign: "center",
align: "left",
width: "136",
type: "string",
editable: true,
},
{
field: "itemlocation",
headerName: " itemlocation",
headeralign: "center",
align: "left",
width: "136",
type: "string",
editable: true,
renderCell: (params) => {
return (
<> </>
);
}
},]
Json data
const Rows =[{
"id": "2433-10",
"busiName": "ABC",
"srTypeId": "2433-10",
"nodeType": "0",
"pathName": "home",
"busiSort": 10,
"itemInfo": "1:sql test question: itemlocation=USA",
"superTypeId": "002",}]
Original MUI Table
itemid
itemname
itemInfo
12
car
1:sql test question: itemlocation=USA
99
toy
1:sql test question: itemlocation=USA
I want extract just itemlocation from itemInfo into New table columns
itemid
itemname
itemInfo
itemlocation
12
car
1:sql test question: itemlocation=USA
USA
99
toy
1:sql test question: itemlocation=USA
CHAIN
If you already have access to itemInfo you could run a method similiar to below
const extractLocation = (itemInfo) => {
return itemInfo.match(/itemlocation=(.*)/)[1]
}
This uses regular expression matching to find just the text after itemlocation. If you expect other text that isnt the location to be added to your itemInfo string later on you can update it to exclude that text.
To call this method(assuming your json data is an array of object) you could do.
const location = extractLocation(json[0]['iteminfo'])
// or for all locations
const locations = json.map((item) => {
return extractLocation(item['itemInfo'])
}
let newFormat = items.map(item => {
return {
newProperty: item.oldProperty
}
});

Updating Columns Dynamically - Alloy UI

I'm trying to change columns dynamically in my Alloy UI DataTable - depending on what button is selected, columns are changed depending on which data is returned.
My columns get updated, however the actual data is never included in the table. When I don't define any columns both the columns and data are returned - I of course want control of how my columns are displayed and want to set their attributes
Below is my code:
var dataTable = new Y.DataTable({ //Defining Datatable with no columns preset
editEvent: 'dblclick',
plugins: [{
cfg: {
highlightRange: false
}]
});
button.on(
'click', //On Click...
function() {
var category = $(this).attr("id"); //value retrieved from id of button selected
dataSource = new Y.DataSource.IO({source: '/searchMyData
dataSource.sendRequest({
dataType: 'json',
on: {
success: function(e) {
response = e.data.responseText;
setColumnNames(category); //Set the Columns...
data = Y.JSON.parse(response);
dataTable.set('data', data);//Then the Data
dataTable.render('#my-container');
},
failure: function() {
alert(e.error.message);
}
}
});
function setColumnNames(tabName){ //Defining Columns
var columns1 = [
{ key: 'id', label: 'ID', width: '70px' },
{ key: 'name', label: 'Name', width: '70px' }
];
var columns2 = [
{ key: 'id', label: 'ID', width: '70px' },
{ key: 'addr', label: 'Address', width: '70px' }
];
switch (category) {
case "person":
dataTable.set('columns', columns1);
break;
case "address":
dataTable.set('columns', columns2);
break;
default:
console.log('');
}
There's no issue with the data returning from the ajax request, only when it comes to loading it to the table with a new set of columns defined. I've tried the reset() method on both columns and data on each click, but no luck.
It turns out the keys returned from my request were being capitalized and included underscores (just how they're defined in the database) - I've also noticed defining the columns key is case sensitive. If I changed a single character from lower case to upper than the column would not display data.

getting additional value fields from data source for dx.chartjs doughnut chart

For my chart, I use pieChartDataSource as my doughnut chart's data source. I've been pouring over the documentation to figure out a way to, instead of labeling the segments with valueField, display an additional field that is not the argumentField.
In my console, I know that pieChartDataSource has the field I am looking for. It is an array of objects. Each object has several fields of which I have product as the argumentField and count as the valueField. My presumption is that I somehow have to use the tagField in order to pass additional properties.
To reiterate, I want to display owner (a third value), instead of product in the segment label of my chart. How would I customize the label so that it shows the owner?
// ...
dataSource: pieChartDataSource,
// ...
series: { type: 'doughnut',
argumentField: 'product',
valueField: 'count',
tagField: 'owner',
valueType: 'numeric',
label: { visible: true,
font: {
family: 'sans-serif',
},
connector: { visible: false },
radialOffset: 0,
position: 'inside',
rotationAngle: 0,
customizeText: function () {/* use tagField here? */},
},
// ...
Can retrieve tag from point, that is an attribute of customizeText parameter
label: {
customizeText: function () {
return this.point.tag;
}
}

Kendo + Angular chart data

I'm trying out Kendo charts with angular, and I have problem displaying data, here is my code:
HTML:
<div kendo-chart="rchart" data-k-options="chartOptions" data-role="chart" class="k-chart" style="position: relative;"></div>
Javascript:
resultService.getResult().then(function (resultResponse) {
$scope.data = resultResponse.data;
$scope.oldReps = _.pluck($scope.data.TreningScores.Item1, 'Item2');
$scope.newReps = _.pluck($scope.data.TreningScores.Item2, 'Item2');
$scope.categories = _.pluck($scope.data.TreningScores.Item1, 'Item1');
});
$scope.chartOptions = {
legend: {
position: "bottom"
},
seriesDefaults: {
type: "column"
},
series: [{
name: "Total Visits",
data: $scope.oldReps
}, {
name: "Unique visitors",
data: $scope.newReps
}],
valueAxis: {
line: {
visible: false
}
},
tooltip: {
visible: true,
format: "{0}"
}
};
The problem is chart isn't updated after data is fetched from server, I've tried refreshing chart like this (but with no luck):
$scope.chart = {
refreshChart : function() {
$scope.rchart.refresh();
},
};
And calling this method in:
resultService.getResult().then(function (resultResponse) {});
And I've also tried to define $scope.chartOptions inside same function, but nothing. Is there any way to fix this ?
It's not well documented, but to get a UI control with remote data-binding to update after data has been returned from a server requires both watching the collection for updates from the Angular side and rebinding the data object to its respective UI control from the Kendo side.
In your controller, watch for changes to your data objects using $watchCollection, and update the objects/properties which are bound to those collections:
// API call
$http.get('...').success(function(data){
$scope.data = data;
});
// KendoUI config object
$scope.chart = {
dataSource: {
data: $scope.data
}
};
// Watch for changes to $scope.data
$scope.$watchCollection('data', function(newData) {
// Update data bindings with changes
$scope.chart.dataSource.data = newData;
});
In your view, define the object your UI control should be bound to when changes are made via the k-rebind Angular-Kendo directive:
<div kendo-chart k-options="chart" k-rebind="chart"></div>
Here is an example of a chart bound to remote data:
http://codepen.io/micjamking/pen/4980a5e22cbd4de01264fadae5f25f06
The use of $watchCollection to track and assign the dataSource.data in the accepted answer and others is a needlessly convoluted approach.
Here's a straightforward implementation:
view:
<div kendo-chart k-theme='metro' k-options="chart" k-rebind="chart"></div>
controller:
$scope.chart = {
dataSource: new kendo.data.DataSource({
data: [{ title: "Loading", value: 100, color: '#EFEFEF' }]
}),
series: [{ field: 'value', categoryField: 'title', padding: 0, holeSize: 25 }],
seriesDefaults: { type: 'donut', startAngle: 90 }
};
Using the dataSource.data() method instead of assigning dataSource.data as an array is the key here:
payrollService.load(userId).then(function (result) {
$scope.chart.dataSource.data(result.items); //where result.items is an array like so:
//[
// { title: "Net Pay", value: 60, color: '#6BAE4B' },
// { title: "Taxes", value: 15, color: '#ED6347' },
// { title: "Deductions", value: 25, color: '#8161C2' }
//]
});
Codepen Demo:
http://codepen.io/TaeKwonJoe/pen/WGOpEv
I think your problem is that $scope.chartOptions is set before the data of the resultService is retrieved. Angular is returning an empty array in this case and filling in the data later.
But $scope.chartOptions not not updated with new data.
You could try with
$scope.$watchCollection('oldReps', function(newData, oldData) {
$scope.chartOptions.series[0].data = newData;
});
$scope.$watchCollection('newReps', function(newData, oldData) {
$scope.chartOptions.series[1].data = newData;
});
So chartOptions are updated if oldReps or newReps have changed.
I had a similiar problem and $watchCollection saved my day (Caching data and updating another object for an chart does not work)

DataTables add object data that is not a column to row?

I can't figure this one out, their API is very confusing.
I have a table that displays tabular data of geometric features, so I want to have the coordinates saved in the row data.
And I need a way to retrieve this coordinates, for example, when a user clicks on the row.
Example of what I'm trying to achieve :
const dt = $('table').DataTable({
columns : [
{data : "NAME"},
{data : "COLOR"}
]
})
dt.row.add({
COLOR : "Red",
NAME : "Point1",
//Invalid parameter error
geometry : {
type : "point",
coordinates : [1,1]
}
})
I think it wouldn't be ideal storing in a hidden column, because the coordinates can get quite large for polygon types.
I'm very new to DataTables and am very confused with the API, any suggestion on how to better organize/execute my concept is more than welcome.
Seems like what you have should work. I put together a little example for you:
http://live.datatables.net/rikofefu/1/edit
It adds a row with the extra geometry object. Select the row then click the Show selected data button. The console will display the full row and just the geometry object.
I'm using the Select extension to get the selected row.
HTML
<table>
<thead>
<tr>NAME</tr>
<tr>COLOR</tr>
<tr></tr>
</thead>
</table>
JS
const dt = $('table').DataTable({
columns: [
{data: null},
{data: null},
{data: null}
],
// This makes the row clickable, where you can get data later
"createdRow": function (row, data, dataIndex) {
var tds = $(row).find("td");
$.each(tds, function (key, value) {
$(value).attr("onclick", "see_the_data(this)");
}
},
// this hides the coordinate column from view
"columnDefs": [
{
"targets": 2,
"visible": false
}
]
});
dt.row.add({
COLOR: "Red",
NAME: "Point1",
//Invalid parameter error
geometry: {
type: "point",
coordinates: [1, 1]
}
});
function see_the_data(e) {
console.log("the data is ", e); // you can then go further as you need
}

Categories

Resources