Unknown Parameter Error for Datatable with dynamic columns being displayed - javascript

It keeps throwing unknown parameter S.N. on row 0 column 0. This is shown twice and then it exits. The columns are fetched via ajax and so are the data.
The structure is constructed correctly. Checked it with the console.
But this error pops up and the datatables is empty.
The no.of columns are correct tho but without any data.
if (response.isOk == true)
{
var data = new Array();
var columns = JSON.parse(response.responseObject.columns);
var counter = 1;
$.each(response.responseObject.data, function(index, value)
{
var datum = new Array();
$.each(columns, function(ind, val)
{
if (val.data == "S.N.")
{
datum.push(counter);
}
else
{
datum.push(value[val.data]);
}
});
counter++;
data.push(datum);
});
if (tabReport != "")
{
tabReport.destroy();
}
tabReport = $("#tabReport").DataTable
(
{
dom: "Bfrtip",
columns: columns,
buttons:
[
{
extend: "excelHtml5",
text: 'Download',
titleAttr: "Excel"
}
],
data: data
}
);
}

`var columns =
[
[data: "asd"],
[data: "asd"],
[data: "asd"]
];`
This is the desired format for the data table.

Related

I'm getting duplicate firestore data array using DataTables plugin

I'm using the DataTable plugin, populating the table with data from Firebase Firestore database.
But I'm getting multiple data-set arrays
which continues till it reaches the length of data in the db.
Also, getting some errors
DataTables warning: table id=dataTable - Requested unknown parameter '5' for row 0, column 5. For more information about this error, please see http://datatables.net/tn/4
and
DataTables warning: table id=dataTable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
But after I skip through all the errors, I get the Firestore data in the table.
Here is the code I'm using to get the data from Firestore and populating in the table;
$(document).ready(function () {
var dataSet = new Array();
var query = db.collection('news').orderBy('timestamp');
let observer = query.onSnapshot(snapshot => {
let changes = snapshot.docChanges();
changes.forEach(change => {
if (change.type == 'added') {
dataSet.push([change.doc.data().newsTitle,
change.doc.data().newsContent,
change.doc.data().newsImage,
change.doc.data().newsPublisher,
change.doc.data().timestamp.toDate()]);
console.log("data", dataSet);
const dataTable = $('#dataTable').DataTable({
data: dataSet,
order: [0, 'desc'],
columns: [
{ title: 'Title' },
{ title: 'Content' },
{ title: 'Picture' },
{ title: 'Publisher' },
{ title: 'Date' },
{ title: 'Action' }
]
});
dataTable.clear();
dataTable.rows.add(dataSet);
dataTable.draw();
}
})
});
})
What can I do to resolve this?
Figured it out, just removed the dataTable.rows.add(dataSet) from the loop.
$(document).ready(function () {
var dataSet = new Array();
var query = db.collection('news').orderBy('timestamp');
let observer = query.onSnapshot(snapshot => {
let changes = snapshot.docChanges();
changes.forEach(change => {
if (change.type == 'added') {
dataSet.push([change.doc.data().newsTitle,
change.doc.data().newsContent,
change.doc.data().newsImage,
change.doc.data().newsPublisher,
change.doc.data().timestamp.toDate()]);
}
})
console.log("data", dataSet);
const dataTable = $('#dataTable').DataTable({
data: dataSet,
order: [0, 'desc'],
columns: [
{ title: 'Title' },
{ title: 'Content' },
{ title: 'Picture' },
{ title: 'Publisher' },
{ title: 'Date' },
{ title: 'Action' }
]
});
dataTable.clear();
dataTable.rows.add(dataSet);
dataTable.draw();
});
})
But I'm still getting the alert error below twice, any ideas?
DataTables warning: table id=dataTable - Requested unknown parameter '5' for row 0, column 5. For more information about this error, please see http://datatables.net/tn/4

Deleted selected rows from JQuery Datatables

How do I delete my selected rows from datatables that use a local array for data? This is how I initialised my table:
var selected = Array();
var dataSet = [];
var rowItem = "";
$(document).ready(function () {
var table = $("#table").DataTable({
"data": dataSet,
"filter":false,
"language": {
"search": "",
"searchPlaceholder": " Search"
},
"select": {
"style": 'multi'
},
"ordering": true,
"lengthChange": false,
"columns": [
{ "title": "Name"},
],
"responsive": true,
"processing":true,
}).columns.adjust()
.responsive.recalc();
new $.fn.dataTable.FixedHeader(table);
This is how I'm trying to delete the selected rows from my tables:
$("#roleSection").on("click","#removeRole",function (e) {
selected = table.rows('.selected').data().toArray();
console.log(selected);
$.each(selected, function (id, value) {
console.log(value);
dataSet.splice($.inArray(value, dataSet), 1);
table.row(selected).remove().draw();
});
console.log(dataSet);
return false;
});
For some reason the items that are not deleted are being deleted and the table does not get updated at all.
I think you can find your answer over here
Basically, you have to change your line selected = table.rows('.selected').data().toArray(); to table.rows( '.selected' ).remove().draw();
And remove the additional code.
You also don't have to worry about looping through the list because table.rows('.selected') gets all the rows with the class selected and then remove() deletes them all for you.
Edit: If the dataSet is not updated automatically, then I think this might answer your second query
$("#delete").on("click", function (e) {
let newDataSet = [];
table.rows( '.selected' ).remove().draw();
table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
let row = this;
newDataSet.push(row.data());
});
dataSet = newDataSet;
});

DevExtreme / Knockout.js implement JSON as datasource

I'm new to JavaScript and REST, and I need to implement JSON as datasource to devextreme using knockout.js.
My problem is, that I can fetch the json, but it is not added to the datasource. I used console.log() for testing and noticed that the json is correctly loaded, but the datasource is empty (see comments in code below). How can I achieve the usage of my json as datasource?
Note: I used DevExtreme load JSON as datasource using knockout as base for getting my JSON-contents.
I have a sample JSON-File looking like this:
{
"ID":"3",
"content":
{
"ProdId":"000176491264",
"ProdDesc":"Sample 1",
"Type":"A",
}
}
And my current viewmodel looks like this:
MyApp.overview = function (params) {
"use strict";
var getData = function () {
var deferred = $.Deferred();
var xmlhttp = new XMLHttpRequest(), json;
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
json = JSON.parse(xmlhttp.responseText);
// prints needed content:
console.log(json.content);
deferred.resolve(json.content);
}
};
xmlhttp.open('GET', 'http://localhost:56253/test/3?format=json', true);
xmlhttp.send();
return deferred.promise();
};
var viewModel = {
overviewDatagridOptions: {
dataSource: getData(),
selection: {
mode: "single"
},
columns: [{
dataField: "ProdId",
caption: "ID"
}, {
dataField: "ProdDesc",
caption: "Description"
}, {
dataField: "Type",
caption: "Type"
}],
rowAlternationEnabled: true
},
// Returns {}
console.log("Datasource: " + JSON.stringify(viewModel.overviewDatagridOptions.dataSource));
return viewModel;
};
Edit: I changed my datasource to this:
dataSource: {
load: function (loadOptions) {
var d = new $.Deferred();
var params = {};
//Getting filter options
if (loadOptions.filter) {
params.filter = JSON.stringify(loadOptions.filter);
}
//Getting sort options
if (loadOptions.sort) {
params.sort = JSON.stringify(loadOptions.sort);
}
//Getting dataField option
if (loadOptions.dataField) {
params.dataField = loadOptions.dataField;
}
//If the select expression is specified
if (loadOptions.select) {
params.select= JSON.stringify(loadOptions.select);
}
//Getting group options
if (loadOptions.group) {
params.group = JSON.stringify(loadOptions.group);
}
//skip and take are used for paging
params.skip = loadOptions.skip; //A number of records that should be skipped
params.take = loadOptions.take; //A number of records that should be taken
var obj;
$.getJSON('http://localhost:56253/test/3?format=json', params).done(function (data) {
d.resolve(data);
});
//return obj;
return d.promise();
}, [...]
Based on the demo found here: https://www.devexpress.com/Support/Center/Question/Details/KA18955
Now, the output from the datasource is no longer empty, and looks like this:
Object
- load:(loadOptions)
- arguments:(...)
- caller:(...)
- length:1
- name:"load"
- prototype:Object
- __proto__:()
- [[FunctionLocation]]
- [[Scopes]]:Scopes[1]
- totalCount:(loadOptions)
- arguments:(...)
- caller:(...)
- length:1
- name:"totalCount"
- prototype:Object
- __proto__:()
- [[FunctionLocation]]
- [[Scopes]]:Scopes[1]
- __proto__:Object

Binding non-boolean values to CheckBox in Table

I am having trouble to bind a String value of 00 and 98 to false and true. I have found quite a few possible solutions but none of them works for me and I don't quite understand why.
Suppose I receive data from a server and create a JSON Model and set that to the table model.
function createTableColumns(columns) {
var oTable = sap.ui.getCore().byId("mainTable");
var statusTemplate = new sap.ui.commons.CheckBox({
editable: false,
// THIS WAS MY FIRST ATTEMPT TO GET IT WORKING
//checked: {
// path: "{TableModel>status}",
// formatter: function(val) {
// console.log(val);
// return val === "98";
// }
//}
});
// SECOND ATTEMPTS, DOESN'T WORK EITHER
statusTemplate.bindProperty("checked", "{TableModel>status}", function(val) { return val === "98"; });
for(var i = 0; i < columns.length; i++) {
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: columns[i]}),
name: columns[i],
flexible: false,
autoResizable: true,
template: columns[i] === 'status' ? statusTemplate : new sap.ui.commons.TextView({text: "{TableModel>" + columns[i] + "}"}),
sortProperty: columns[i],
filterProperty: columns[i],
}));
}
}
Both ways in the code above do not work. I don't know whether it is the logic or whether I am using the model wrong. Every other (TextView) Column displays data to which it is bound... so I believe that the binding is correct!?
I also have tried this way but that doesn't work at all for me: OpenUI5 binding property with a function, instead of direct access
I keep on getting the error that "00" is not a valid value for the checkbox.
Am I doing something obviously wrong?
EDIT: Current state
This function is basically called everytime the user switches
the table in the application. The old data (rows and columns) will be
deleted and filled new. The parameter columns contains an array of
strings of the column names! No data is in the data model yet!!!
function createTableColumns(columns) {
var oTable = sap.ui.getCore().byId("mainTable");
oTable.destroyColumns();
sap.ui.getCore().setModel(null, "TableModel");
var statusCheckBoxTemplate = new sap.ui.commons.CheckBox({
text: "{TableModel>status}",
editable: false,
checked: {
path: "{TableModel>status}",
formatter: function(v) {
console.debug(v);
if(v === "98") return true;
else return false;
}
}
});
for(var i = 0; i < columns.length; i++) {
if(columns[i] !== 'rowid') {
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: columns[i]}),
name: columns[i],
flexible: false,
autoResizable: true,
template: columns[i] === 'status' ? statusCheckBoxTemplate : new sap.ui.commons.TextView({text: "{TableModel>" + columns[i] + "}"}),
sortProperty: columns[i],
filterProperty: columns[i],
}));
}
}
}
After a user selected a table to display it sits there only displaying
the columns. Data is fetched from the server (ajax call) as an JSON object and a data model is created. It all works fine. Data is bound without problems and displayed correctly.
function tableBtnReloadPressed() {
// ajax call
var tabledata = readTableData(ACTIVE_TABLE);
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(tabledata);
sap.ui.getCore().setModel(oModel, "TableModel");
var oTable = sap.ui.getCore().byId("mainTable");
oTable.setModel(oModel);
oTable.bindRows("TableModel>/");
}
EDIT: Third try with factory
function createTableColumns(columns) {
var oTable = sap.ui.getCore().byId("mainTable");
oTable.destroyColumns();
sap.ui.getCore().setModel(null, "TableModel");
sap.ui.model.SimpleType.extend("BooleanStringType", {
formatValue: function(s) {
console.debug(typeof s, s);
return s === "98";
},
parseValue: function(s) {
console.debug(typeof s, s)
return s ? "98" : "00";
},
validateValue: function(s) {
console.debug(typeof s, s)
}
});
var statusCheckBoxTemplate = new sap.ui.commons.CheckBox({
text: "{TableModel>status}",
editable: false,
//checked: {
// path: "{TableModel>status}",
// formatter: function(v) {
// console.debug(v);
// if(v === "98") return true;
// else return false;
// }
//}
});
statusCheckBoxTemplate.bindProperty("checked", {
path: "{TableModel>status}",
type: new BooleanStringType()
});
for(var i = 0; i < columns.length; i++) {
if(columns[i] !== 'rowid') {
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: columns[i]}),
name: columns[i],
flexible: false,
autoResizable: true,
template: columns[i] === 'status' ? statusCheckBoxTemplate : new sap.ui.commons.TextView({text: "{TableModel>" + columns[i] + "}"}),
sortProperty: columns[i],
filterProperty: columns[i],
}));
}
}
}
You should simplify to get it working. First thing is to use a textview / label to check if the binding is working. Only then change to the checkbox and use a formatter / custom datatype for the conversion.
For instance, this is not valid (from the code above):
checked: {
path: "{TableModel>status}",
because when you pass an explicit path property, you should not use the {} in the string.
Ok, I put this into jsbin and played arount wiht it a bit. jsbin with solution
The correct template for the checkbox is this:
var statusCheckBoxTemplate = new sap.ui.commons.CheckBox({
text: "{TableModel>status}",
editable: false,
checked: {
path: "TableModel>status",
formatter: function(v) {
return(v === "98");
}
}
});
Edit: #jumpifzero beat me to it. But I wanted to edit my post for a complete picture. Such an easy to miss answer. ^^"

Ext.grid.CheckboxSelectionModel not returning proper id values when multipal rows are checked in the grid

im using extjs3 . my problem is im loading the store from server side using ajax . as follows
var store_dept = new Ext.data.JsonStore({
totalProperty:'totalcount',
root:'rows_dept',
autoLoad:true,
url: '<%=getResultURL.toString()%>',
fields:[
{ name:'name'},
{ name:'id'},
{ name:'address'}
]
});
var sm_dept = new Ext.grid.CheckboxSelectionModel(
{
singleSelect: false,
checkOnly: false,
listeners: {
selectionchange: function(sm_dept) {
}
}
}
);
now im getting the response so im formatting it in renderer column as
function renderBufferResult_dept(value, p, record){
return String.format('<div style="white-space:normal !important;"><b>{1}</b><br/>{3}<br/>{2}<br/></div>',value,record.data.name,record.data.address,record.data.id);
}
the grid code is :
var grid_dept= new Ext.grid.GridPanel({
id:'resgriddept',
width:210,
height:300,
title:'Additional Notification',
store: store_dept,
trackMouseOver:false,
disableSelection:true,
loadMask: true,
sm:sm_dept,
// grid columns
columns:[
sm_dept,
{
header: "Details",
dataIndex: 'id',
width:210,
sortable: true,
renderer:renderBufferResult_dept
}
] ,
buttons: [
{
text:'Export To Excel',
handler: function()
{
if(property_list!=''){
/* var prop_list='';
for(var i=0 ;i<sm.selections.getCount();i++){
prop_list =prop_list+ sm.selections.get(i).data.id+',';
} */
window.open('<%=getxlFileURL%>'+'&id_list='+property_list);
}else{
alert('Select propert to Export');
}
}
},{
text:'Generate Letter',
handler: function()
{
var dept_id_list = '0,';
if(sm_dept.selections.getCount()>0){
alert('cont select');
for(var j=0 ;j<sm_dept.selections.getCount();j++){
alert("id "+sm_dept.selections.get(j).data.id);
dept_id_list = dept_id_list+sm_dept.selections.get(j).data.id+',';
alert('id with templist '+dept_id_list);
}
}
window.open('<%=getreportsURL%>'+'&id_list='+property_list+'&dept_id_list='+dept_id_list);
}
}],
buttonAlign:'center'
});//End Of Grid
// render it
grid_dept.render('res-grid-dept');
store_dept.load();
The problem comes when i hit generate letter button, the id's of the checked rows(1,2,3) comes like 0,1,1,2 when it must come like 0,1,2,3 in the alert.
This is happening because you use get method of MixedCollection while you should use itemAt. In api you can read that this method returns the item associated with the passed key (id in your case) OR index and that key has priority over index. So when you pass 0 then this is treated as index, because you don't have such key and for that index id is 1. But when you pass 1 then it is treated as key (id in other words) so it returns item with id 1.
Replace alert("id "+sm_dept.selections.get(j).data.id); with alert("id "+sm_dept.selections.itemAt(j).data.id); and you'll be good.

Categories

Resources