Uncaught TypeError in jsPdf autotable - javascript

Am trying to print the dynamic data's into pdf file using jsPdf Auto-table . When am doing this i got some kind of error's like
The headers should be an object or array, is: function (jspdf.plugin.autotable.js:10 )
The data should be an object or array, is: function (jspdf.plugin.autotable.js:10)
TypeError: t.forEach is not a function (angular.js:12314)
Here is my code -
var getColumns = function () {
return [
{ title: "ID", dataKey: "id" },
{ title: "Name", dataKey: "first_name" },
{ title: "Email", dataKey: "email" },
{ title: "City", dataKey: "city" },
{ title: "Country", dataKey: "country" },
{ title: "Expenses", dataKey: "expenses" }
];
};
function getData(mainSteps) {
mainSteps = mainSteps || 4;
//var sentence = faker.lorem.words(12);
var data = [];
for (var j = 1; j <= rowCount; j++) {
data.push({
id: j,
first_name: this.getSteps(),
email: this.getSteps(),
country: this.getSteps(),
city: this.getSteps()(),
expenses: this.getSteps()
// text: shuffleSentence(sentence),
//text2: shuffleSentence(sentence)
});
}
return data;
}
var pdfsize = 'a4';
var doc = new jsPDF('p', 'pt', pdfsize);
doc.autoTable(getColumns, getData, {
theme: 'grid', // 'striped', 'grid' or 'plain'
headerStyles: {
fillColor: [12, 234, 227],
textColor: [12, 1, 1]
},
// margin: { top: 50, left: 20, right: 20, bottom: 0 },
styles: {
overflow: 'linebreak',
columnWidth: 88
},
beforePageContent: function (data) {
doc.text("Process Name :" + mainData.name + " || " + "Description :" + mainData.description, 40, 30);
},
//startY: doc.autoTableEndPosY() + 20,
columnStyles: {
0: { columnWidth: 200 }
}
});
//startY: doc.autoTableEndPosY() + 20
doc.save(mainData.name + ".pdf");
Note : If the error is in my code mean's i can find the solution for that, But it says error is in (jspdf.plugin.autotable.js:10 ) and (angular.js:12314) so am getting confused here. Can someone clarify me please.

As the errors explain the input data must be arrays or objects. In your case that simply means calling the functions instead of sending them to autotable. Replace this
doc.autoTable(getColumns, getData, {...});
with
doc.autoTable(getColumns(), getData(), {...});

Related

Build table dynamically with PDFmake

I found an example of how to fill the table with pdfmake dynamically, which has 2 columns. Now I tried add another column 'height' to the table but I don't know how to modify it.
function buildTableBody(data, columns) {
var body = [];
body.push(columns);
data.forEach(function(row) {
var dataRow = [];
columns.forEach(function(column) {
dataRow.push(row[column].toString());
})
body.push(dataRow);
});
return body;
}
function table(data, columns) {
return {
table: {
headerRows: 1,
body: buildTableBody(data, columns)
}
};
}
function Pdftest(){
var externalDataRetrievedFromServer = [
{ name: 'Bartek', age: 34, height: 1.78 },
{ name: 'John', age: 27, height: 1.79 },
{ name: 'Elizabeth', age: 30, height: 1.80 },
];
var dd = {
content: [
{ text: 'Dynamic parts', style: 'header' },
table(externalDataRetrievedFromServer, ['name', 'age', 'height'])
]
}
pdfMake.createPdf(dd).download();
}
Does anybody know what needs to be modified?
Error was anywhere else, the code above works perfectly fine

javascript code not picking up code_description value for first record

I have something similar to the JSFiddle mentioned here. The JSFiddle works fine, however, I am seeing a strange behaviour in my code. The description of very first
cell is always empty even though I am seeing that in the returned data (in JSON format) from the webservice, the description is present for each record. Please
take a look at the code below and let me know if I am missing anything:
this.processEmployees = function (data_, textStatus_, jqXHR_) {
var collection = data_.employees;
// A helper function used for employee codes below.
var isUsedKey = function (arrayOfObject, key) {
for (var i = 0; i < arrayOfObject.length; i += 1) {
if (arrayOfObject[i].key == key) {
return true;
}
}
return false;
};
var employeeCodes = [];
for (var i = 0; i < collection.length; i++) {
if (i == 0) {
var newItem = {};
newItem.key = collection[i].code_value;
newItem.dates = [collection[i].code_assignment_date];
newItem.description = collection[i].code_description;
newItem.hiringCriterion = collection[i].hiring_criteria;
newItem.name = collection[i].name;
console.log("Would like to check code_description for first item:",collection[i].code_description);
//debugger;
employeeCodes.push(newItem);
} else {
var item = collection[i];
var itemName = item.code_value;
var itemDate = item.code_assignment_date;
var itemDescription = item.code_description;
var hiringCriterion = item.hiring_criteria;
var itemCodeName = item.name;
if (isUsedKey(employeeCodes, itemName)) {
for (var j = 0; j < employeeCodes.length; j++) {
if (employeeCodes[j].key == itemName) {
var index = employeeCodes[j].dates.length;
employeeCodes[j].dates[index] = itemDate;
}
}
} else {
var nextNewItem = {};
nextNewItem.key = itemName;
nextNewItem.dates = [itemDate];
nextNewItem.code_description = itemDescription;
nextNewItem.hiring_criteria = hiringCriterion;
nextNewItem.name = itemCodeName;
employeeCodes.push(nextNewItem);
}
}
}
var newSource = {
localdata: employeeCodes,
datafields: [{
name: 'code_value',
type: 'string',
map: 'key'
},
{
name: 'code_assignment_date',
type: 'date',
map: 'dates>0'
},
{
name: 'name',
type: 'string'
},
{
name: 'code_description',
type: 'string'
},
{
name: 'hiring_criteria',
type: 'string'
}
],
datatype: "array"
};
var newAdapter = new $_.jqx.dataAdapter(newSource);
var iconrenderer = function (row, columnfield, value, defaulthtml, columnproperties) {
var icon = '';
if (employeeCodes[row].dates.length > 1) {
icon = '<img src="images/icon-down.png" style="position: absolute; right: 5px;" />';
}
return '<span style="position: relative; width: 100%; margin: 4px; float: ' + columnproperties.cellsalign + ';">' + newAdapter.formatDate(value, 'd') + icon + '</span>';
};
$_(self.gridSelector).jqxGrid({
source: newAdapter,
editable: true,
width: '600',
pageable: true,
sortable: true,
autoheight: true,
theme: 'classic',
height: '170',
columnsResize: true,
columns: [
{
text: 'Employee Name',
datafield: 'name',
width: 85,
},
{
text: 'Code Value',
datafield: 'code_value',
width: 75,
editable: false
},
{
text: 'Latest Date(s)',
datafield: 'code_assignment_date',
cellsformat: 'd',
columntype: 'combobox',
width: 100
createeditor: function (row, column, editor) {
var info = $_(self.gridSelector).jqxGrid('getrowdata', row);
console.log("length of info: " + info);
var groupName = info.code_value;
console.log("Contents of groupName: " + groupName);
var dates = [];
for (var i = 0; i < employeeCodes.length; i++) {
if (employeeCodes[i].key == groupName) {
dates = employeeCodes[i].dates;
}
}
editor.jqxComboBox({ autoDropDownHeight: false, source: dates, promptText: "Previous Date(s):", scrollBarSize: 10 });
},
initeditor: function (row, column, editor) {
var info = $_(self.gridSelector).jqxGrid('getrowdata', row);
var groupName = info.code_value;
var dates = [];
for (var i = 0; i < employeeCodes.length; i++) {
if (employeeCodes[i].key == groupName) {
dates = employeeCodes[i].dates;
}
}
editor.jqxComboBox({
autoDropDownHeight: false,
source: dates,
promptText: "Dates:",
width: 100,
scrollBarSize: 10,
renderer: function (index_, label_, value_) {
return formatDateString(value_);
},
renderSelectedItem: function (index, item) {
var records = editor.jqxComboBox('getItems');
var currentRecord = records[index].label;
return formatDateString(currentRecord);;
}
});
},
cellvaluechanging: function (row, column, columntype, oldvalue, newvalue) {
// return the old value, if the new value is empty.
if (newvalue == "") return oldvalue;
}
},
{
text: 'Description',
datafield: 'code_description'
},
{
text: 'Hiring Criterion',
datafield: 'hiring_criteria',
editable: false,
hidden: true
}
],
});
}; // End of processEmployees
For Example, if my JSON is the following:
{
"employees": [{
"code_value": "B1",
"code_assignment_date": "2016-12-13 23:04:00.0",
"code_type": 7,
"code_description": "This employee has received his salary",
"name": "Peter",
"hiring_criteria": null
}, {
"code_value": "A1",
"code_assignment_date": "2016-05-20 05:00:00.0",
"code_type": 7,
"code_description": "Employee has 5 vacation days left",
"name": "Jack",
"hiring_criteria": null
}],
"webServiceStatus": {
"status": "SUCCESS",
"message": "2 results"
}
}
I am not seeing the very first code_description value which is This employee has received his salary in the above JSON response whereas the following
line mentioned in the above code clearly shows it in the console panel:
console.log("Would like to check code_description for first item:",collection[i].code_description);
newItem.description = collection[i].code_description;
---Replace newItem.description to newItem.code_description in First object condition
newItem.hiringCriterion = collection[i].hiring_criteria;
---Replace newItem.hiringCriterion to newItem.hiring_criteria in First object condition

jQuery dataTable not showing data by default

I have a jquery DataTable as
html page
<div id="content">
</div>
js code
(function ($) {
'use strict';
var module = {
addTable: function () {
var output = '<table id="table1"></table>';
$('#content').append('<p></p>' + output);
var data = [];
data = this.getData();
$('#table1').dataTable({
"data": data,
"columns": [
{
"title": 'Name',
mDataProp: 'name',
width: '20%'
},
{
"title": 'Company',
mDataProp: 'company'
},
{
"title": 'Salary',
mDataProp: 'salary'
}],
'scrollY': '400px',
'scrollCollapse': false,
'paging': false
});
},
getData: function () {
var arr = [];
for (var i = 0; i < 100; i++) {
var obj = {
name: 'John',
company: 'XYZ',
salary: '$XYZ'
};
arr.push(obj);
}
return arr;
}
};
$(document).ready(function () {
$('#content').append('Loading....');
module.addTable();
});
})(jQuery);
On initial load, it shows an empty table. Data comes after performing some search. How to show the data by default on initial load?
This is due to javascripts asynchronicity. getData() is not finished at the time of the dataTable initialization. You could make some refactoring, so getData invokes addTable as a callback instead.
var module = {
addTable: function (data) {
var output = '<table id="table1"></table>';
$('#content').append('<p></p>' + output);
$('#table1').dataTable({
"data": data,
"columns": [
{
"title": 'Name',
mDataProp: 'name',
width: '20%'
},
{
"title": 'Company',
mDataProp: 'company'
},
{
"title": 'Salary',
mDataProp: 'salary'
}],
'scrollY': '400px',
'scrollCollapse': false,
'paging': false
});
},
getData: function (callback) {
var arr = [];
for (var i = 0; i < 100; i++) {
var obj = {
name: 'John',
company: 'XYZ',
salary: '$XYZ'
};
arr.push(obj);
}
return callback(arr);
},
init : function() {
this.getData(this.addTable);
}
};
...
module.init();
init() calls getData(callback) with addTable as param, addTable have had the param data added.
demo -> http://jsfiddle.net/bLzaepok/
I assume your getData code is only per example, and you are using AJAX (or whatever) IRL. Call the callback in the callback :
getData: function (callback) {
$.ajax({
...
success : function(data) {
callback(data);
}
});
}

commit changes on existing records in extjs store

my issue is that I want to update existing store and show the changes on the grid.
What I'm doing to update is :
var record = store.getById(me.internalParameters.editInfo.id);
//console.log(me.InfoEditorPanel.hardwareIdField.value);
record.set('hardwareid', me.InfoEditorPanel.hardwareIdField.value);
record.set('location', me.InfoEditorPanel.locationField.value);
record.set('isActive', me.InfoEditorPanel.isActiveField.value);
record.commit();
store.load();
Here what I use to build the grid.
Utils.getPanelListGrid = function (parameters) {
if (parameters.initParameters == null)
parameters.initParameters = {};
var initParameters = parameters.initParameters;
initParameters.gridColumns = [
{ header: "ID", dataIndex: "id", flex: 1 },
{ header: "Hardware ID", dataIndex: "hardwareid", flex: 1 },
{ header: "Location", dataIndex: "location", flex: 1 },
{ header: "Active", dataIndex: "isActive", flex: 1 }
];
return new Backend.shared.MyDataGrid(parameters);
};
Ext.define(
"shared.MyDataGrid", {
extend: "Ext.grid.Panel",
xtype: "MyDataGrid",
title: "MyDataGrid - Hardcoded values",
initParameters: {
storeIdProperty: null,
},
initComponent: function () {
this.store = Ext.create('Ext.data.Store', {
storeId: 'myStore',
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'items'
}
},
fields: ['id', 'hardwareid', 'location', 'isActive'],
data: {
'items': [{
'id': '123456',
'hardwareid': "HID-159",
'location': "Bedroom",
'isActive': "No"
}, {
'id': '789456',
'hardwareid': "HID-357",
'location': "Kitchen",
'isActive': "Yes"
}, {
'id': '147852',
'hardwareid': "HID-149",
'location': "Guest-room",
'isActive': "Yes"
}
]
}
});
this.columns = this.initParameters.gridColumns;
this.listeners = {
selectionchange: {
scope: this,
fn: function (selectionModel, selectedRecords, eventOptions) {
this.selectedIds = [];
this.selectedItems = [];
if (selectedRecords != null) {
for (var i = 0; i < selectedRecords.length; i++) {
var item = selectedRecords[i].data;
this.selectedIds.push(item[this.initParameters.storeIdProperty]);
this.selectedItems.push(item)
}
}
if (this.initParameters.selectionChangeCallback != null)
this.initParameters.selectionChangeCallback(this.selectedIds, this.selectedItems);
}
}
};
shared.MyDataGrid.superclass.initComponent.call(this);
},
getRecordCount: function () {
return this.getStore().getTotalCount();
},
getSelectedIds: function () {
return this.selectedIds;
},
getSelectedItems: function () {
return this.selectedItems;
}
});
Can anyone please explain what should I do exactly to make the grid show the updated row?
I suggest that use the following code in your 'selectionchange' event.
this.getStore().load({
params:{
'yourModelIdProperty':'selectedId'
}
});
It's call an store proxy. You should write a function for that proxy and load the updated data.

fetchItemByIdentity() doesn't work as expected

I have an ItemFileWriteStore on my page. When I click any row in my DataGrid I can get the id of that row, but then when I try to do fetchItemByIdentity using that id, it always returns null. Any idea why this could be?
I'm using Dojo 1.5.
function getRemoveFormatter(id) {
return '<img src="/images/icons/delete.png" />';
}
function deleteItem(id) {
console.log(id);
window.grid.store.fetchItemByIdentity({
identity: id,
onItem: function(item, request) { console.log(item); }
});
//window.grid.store.deleteItem(id);
}
dojo.ready(function() {
var store = new dojo.data.ItemFileWriteStore({data:{items:[]}});
window.grid = new dojox.grid.DataGrid({
store: store,
structure: [
{ name: "id", field: "id", width: "50px" },
{ name: "Stylist", field: "stylist", width: "100px" },
{ name: "Service", field: "service", width: "200px" },
{ name: "Length", field: "length", width: "50px" },
{ name: "Remove", field: "remove", width: "30px", formatter: getRemoveFormatter }
],
identifier: "id",
label: "id"});
dojo.byId("services_grid").appendChild(grid.domNode);
grid.startup();
observeAppointmentServiceAddClick(window.grid);
getAppointmentItems();
});
Try making a small change in the way you declare the store and the grid. The identifier and label properties belong in the data section of the store next to items.
var store = new dojo.data.ItemFileWriteStore({data:{
items:[],
identifier: "id",
label: "id"}});
window.grid = new dojox.grid.DataGrid({
store: store,
structure: [
{ name: "id", field: "id", width: "50px" },
{ name: "Stylist", field: "stylist", width: "100px" },
{ name: "Service", field: "service", width: "200px" },
{ name: "Length", field: "length", width: "50px" },
{ name: "Remove", field: "remove", width: "30px", formatter: getRemoveFormatter }
]});
Here is a simpler code and answer on jsfiddle.
http://jsfiddle.net/martlark/UkKXW/1/
<html>
<head><!--dojo stuff--></head>
<body>
<div id='store'></div>
<div id='log'></div>
</body>
</html>
dojo.require("dojo.data.ItemFileWriteStore");
var store = null;
function getItem(id) {
store.fetchItemByIdentity({
identity: id,
onItem: function (item, request) {
var v = store.getValue(item, 'value');
dojo.byId('log').innerHTML = 'getItem(' + id + ') =' + v;
}
});
}
dojo.ready(function () {
var items = [];
for (var p = 0; p < 5; p++) {
items.push({
id: p,
value: 'v ' + p
});
}
store = new dojo.data.ItemFileWriteStore({
data: {
identifier: 'id',
items: items
}
});
var gotList = function (items, request) {
var itemsList = "<ul>";
dojo.forEach(items, function (i) {
itemsList += '<li> id:' + p + ' = ' + store.getValue(i,
"value") + "</li>";
});
itemsList += '</ul>';
dojo.byId('store').innerHTML = itemsList;
}
var gotError = function (error, request) {
alert("The request to the store failed. " + error);
}
// Invoke the search
store.fetch({
onComplete: gotList,
onError: gotError
});
getItem('2');
});

Categories