how can I get what will be next auto_increment value using Sequelize?
Using mysql query:
SELECT auto_increment
FROM information_schema.tables
WHERE table_schema = 'skolboz'
AND table_name = "cases";
Response is 7 because last inserted row in Cases is 6.
How can I achieve this using Sequelize? Is it even possible?
Thanks
EDIT:
Here is Sequelize model definition:
module.exports = (sequelize, DataTypes) => {
const Case = sequelize.define('Case', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
caseName: DataTypes.STRING,
constructionSite: DataTypes.STRING,
createdBy: DataTypes.STRING,
dateOfDiscovery: {
type: DataTypes.DATEONLY,
get: function() {
return moment(this.getDataValue('dateOfDiscovery')).format('DD.MM.YYYY')
}},
placeOfDiscovery: DataTypes.STRING,
responsible: DataTypes.STRING,
text: DataTypes.TEXT,
sanction: DataTypes.INTEGER,
forCompany: DataTypes.STRING,
priority: DataTypes.STRING,
isActive: {
type: DataTypes.INTEGER,
defaultValue: 1,
},
wasSended: {
type: DataTypes.INTEGER,
defaultValue: 0,
},
})
Case.associate = (models) => {
Case.hasMany(models.caseimages, {foreignKey: 'id', as: 'images'});
};
return Case
}
Here is controller for creating case and adding photo to it.
async postCaseWithImages(req, res) {
try {
await upload(req, res);
console.log(req.files);
if (req.files.length <= 0) {
return res.send(`Musíte vybrať aspoň 1 fotku`);
}
const uploadsFileNames = [];
const uploadsMimeTypes = [];
const uploadsPath = [];
global.creationDate;
global.koordinatorName;
global.problemName;
global.constructionName;
global.discoveryPlace;
global.responsible;
global.problemText;
global.problemSanction;
global.adressedFor;
global.problemPriority;
global.problemActivity;
global.wasSended;
global.newCaseId;
Case.create({
caseName: req.body.caseName,
constructionSite: req.body.constructionSite,
createdBy: req.body.createdBy,
dateOfDiscovery: req.body.dateOfDiscovery,
placeOfDiscovery: req.body.placeOfDiscovery,
responsible: req.body.responsible,
text: req.body.text,
sanction: req.body.sanction,
forCompany: req.body.forCompany,
priority: req.body.priority,
isActive: req.body.isActive,
})
.then((result) => {
let formatedDate = moment(result.createdAt).format(
"DD.MM.YYYY, HH:mm:ss"
);
creationDate = formatedDate;
koordinatorName = result.createdBy;
problemName = result.caseName;
constructionName = result.constructionSite;
discoveryPlace = result.placeOfDiscovery;
responsible = result.responsible;
problemText = result.text;
problemSanction = result.sanction;
adressedFor = result.forCompany;
problemPriority = result.priority;
problemActivity = result.isActive;
wasSended = result.wasSended;
newCaseId = result.id;
})
.catch((err) => {
console.log(err);
res.status(500).send({
error: "Nepodarilo sa vytvoriť nedostatok z dôvodu: ",
err,
});
})
.then(() => {
const checkId = Case.findOne({ where: {id: newCaseId }});
if (checkId == null) {
res.status(400).send({ message: 'Prípad so zadaným ID sa nenašiel.'});
return;
}
for(let i=0;i<req.files.length;i++){
uploadsFileNames.push(req.files[i].filename);
uploadsMimeTypes.push(req.files[i].mimetype);
uploadsPath.push(req.files[i].destination);
CaseImage.create({
fileName: uploadsFileNames[i],
mimeType: uploadsMimeTypes[i],
caseId: newCaseId,
path: uploadsPath[i],
})
}
let doc = new PDFDocument({ margin: 30, size: "A4", compress:false });
doc.pipe(
fs.createWriteStream(`pdf/${problemName}_${creationDate}` + ".pdf")
);
doc.image('logo.png', 485, 10, {width: 100})
const photosToPdf = [];
let positionX = 30;
let positionY = 240;
for(let j=0;j<uploadsPath.length;j++){
photosToPdf.push(uploadsFileNames[j]);
}
photosToPdf.forEach(img => {
if(positionX == 555){
positionX = 30
positionY = positionY + 160
}
doc.image(`uploads/${img}`, positionX, positionY, {width: 265});
positionX = positionX + 275
});
const table = {
title: "Zápis koordinátora " + koordinatorName + "zo dna " + creationDate + ".",
divider: {
header: { disabled: false },
horizontal: { disabled: false, width: 0.5, opacity: 1 },
padding: 25,
columnSpacing: 20,
},
headers: [
{ label:"Názov", property: 'name', width: 70, renderer: null },
{ label:"Názov staveniska (stavba)", property: 'construction', width: 80, renderer: null },
{ label:"Vytvoril koordinátor BOZP", property: 'createdName', width: 80, renderer: null },
{ label:"Priorita", property: 'priority', width: 50, renderer: null },
{ label:"Dátum zistenia", property: 'date', width: 80, renderer: null },
{ label:"Zodpovedný za vyriešenie zistenia", property: 'responsible', width: 100, renderer: null },
{ label:"Miesto zistenia", property: 'placeOfDiscovery', width: 90, renderer: null },
],
datas: [
{
options: { fontSize: 10, separation: true},
name: problemName,
construction: constructionName,
createdName: koordinatorName,
priority: problemPriority,
date: creationDate,
responsible: responsible,
placeOfDiscovery: discoveryPlace,
},
],
};
doc.table(table, {
columnSpacing: 10,
padding: 10,
columnsSize: [200,220,135],
align: "center",
prepareHeader: () => doc.font("Helvetica-Bold").fontSize(8),
prepareRow: (row, indexColumn, indexRow, rectRow, rectCell) => {
const {x, y, width, height} = rectCell;
if(indexColumn === 0){
doc
.lineWidth(.5)
.moveTo(x, y)
.lineTo(x, y + height)
.stroke();
}
doc
.lineWidth(.5)
.moveTo(x + width, y)
.lineTo(x + width, y + height)
.stroke();
doc.fontSize(8).fillColor('#292929');
},
});
const table2 = {
divider: {
header: { disabled: false },
horizontal: { disabled: false, width: 0.5, opacity: 1 },
padding: 25,
columnSpacing: 20,
},
headers: [
{ label:"Návrh na udelenie sankcie", property: 'sanction', width: 100, renderer: null },
{ label:"Pre spolocnost", property: 'forCompany', width: 100, renderer: null },
{ label:"Popis problému", property: 'text', width: 350, renderer: null},
],
datas: [
{
options: { fontSize: 10, separation: true},
sanction: 50,
forCompany: adressedFor,
text: problemText,
},
],
};
doc.table(table2, {
columnSpacing: 10,
padding: 10,
columnsSize: [200,220,135],
align: "center",
prepareHeader: () => doc.font("Helvetica-Bold").fontSize(8),
prepareRow: (row, indexColumn, indexRow, rectRow, rectCell) => {
const {x, y, width, height} = rectCell;
if(indexColumn === 0){
doc
.lineWidth(.5)
.moveTo(x, y)
.lineTo(x, y + height)
.stroke();
}
doc
.lineWidth(.5)
.moveTo(x + width, y)
.lineTo(x + width, y + height)
.stroke();
doc.fontSize(8).fillColor('#292929');
},
});
doc.end();
})
.catch((err) => {
console.log(err);
res.status(500)
})
await highPriorityEmail();
res.status(200).send({
message: "Nedostatok bol úspešne vytvorený.",
});
} catch (err) {
console.log(err);
res.status(500);
}
},
Here is route:
app.post('/api/v1/cases/:id/images',
CaseImagesController.postCaseWithImages)
Here is Vue.js function:
async submitCaseWithPhotos() {
const id = this.newId;
const bozpCaseImage = new FormData();
bozpCaseImage.append('multi-files', this.file);
bozpCaseImage.append('caseName', this.caseName);
bozpCaseImage.append('constructionSite', this.$store.state.selectedConstruction);
bozpCaseImage.append('createdBy', this.logedUser);
bozpCaseImage.append('dateOfDiscovery', this.date);
bozpCaseImage.append('responsible', this.responsible);
bozpCaseImage.append('placeOfDiscovery', this.placeOfDiscovery);
bozpCaseImage.append('text', this.text);
bozpCaseImage.append('sanction', this.sanction);
bozpCaseImage.append('forCompany', this.forCompany);
bozpCaseImage.append('priority', this.priority);
CaseImagesService.postImageWithCase(id, bozpCaseImage)
.then((response) => {
console.log(response)
this.$router.push({ name: 'Cases' });
})
.catch((error) => {
console.log(error)
this.error = "Failed to submit data - please try again later.";
});
},
And this is function when I get this.newId:
async getNewCaseId(){
CasesService.index()
.then((response) => {
const resData = response.data;
const responseArray = []
responseArray.push(resData);
const arrayLength = responseArray[0].length;
const lastId = responseArray[0][arrayLength - 1].id
const newId = lastId + 1
console.log(newId);
this.newId = newId;
})
}
Here is working, updated function.
async postCaseWithImages(req, res) {
try {
await upload(req, res);
console.log(req.files);
if (req.files.length <= 0) {
return res.send(`Musíte vybrať aspoň 1 fotku`);
}
const uploadsFileNames = [];
const uploadsMimeTypes = [];
const uploadsPath = [];
global.newCaseId;
global.creationDate;
global.koordinatorName;
global.problemName;
global.constructionName;
global.discoveryPlace;
global.responsible;
global.problemText;
global.problemSanction;
global.adressedFor;
global.problemPriority;
global.problemActivity;
global.wasSended;
global.emailGroup;
Case.create({
caseName: req.body.caseName,
constructionSite: req.body.constructionSite,
createdBy: req.body.createdBy,
dateOfDiscovery: req.body.dateOfDiscovery,
placeOfDiscovery: req.body.placeOfDiscovery,
responsible: req.body.responsible,
text: req.body.text,
sanction: req.body.sanction,
forCompany: req.body.forCompany,
priority: req.body.priority,
isActive: req.body.isActive,
mailingListGroup: req.body.mailingListGroup,
})
.then((result) => {
let formatedDate = moment(result.createdAt).format(
"DD.MM.YYYY, HH:mm:ss"
);
newCaseId = result.id;
creationDate = formatedDate;
koordinatorName = result.createdBy;
problemName = result.caseName;
constructionName = result.constructionSite;
discoveryPlace = result.placeOfDiscovery;
responsible = result.responsible;
problemText = result.text;
problemSanction = result.sanction;
adressedFor = result.forCompany;
problemPriority = result.priority;
problemActivity = result.isActive;
wasSended = result.wasSended;
emailGroup = result.mailingListGroup;
})
.catch(() => {
console.log(err);
res.status(500).send({
error: "Nepodarilo sa vytvoriť nedostatok z dôvodu: ",
err,
});
})
.then(async () => {
const checkId = Case.findOne({ where: {id: newCaseId }});
if (checkId == null) {
res.status(400).send({ message: 'Prípad so zadaným ID sa nenašiel.'});
return;
}
for(let i=0;i<req.files.length;i++){
uploadsFileNames.push(req.files[i].filename);
uploadsMimeTypes.push(req.files[i].mimetype);
uploadsPath.push(req.files[i].destination);
CaseImage.create({
fileName: uploadsFileNames[i],
mimeType: uploadsMimeTypes[i],
caseId: newCaseId,
path: uploadsPath[i],
})
}
let doc = new PDFDocument({ margin: 30, size: "A4", compress:false });
doc.pipe(
fs.createWriteStream(`pdf/${problemName}_${creationDate}` + ".pdf")
);
doc.image('Skolboz_bez_pozadia.png', 500, 25, {width: 100})
const photosToPdf = [];
let positionX = 30;
let positionY = 240;
for(let j=0;j<uploadsPath.length;j++){
photosToPdf.push(uploadsFileNames[j]);
}
photosToPdf.forEach(img => {
if(positionX >= 550){
positionX = 30
positionY = positionY + 215
}
doc.image(`uploads/${img}`, positionX, positionY, {width: 265});
positionX = positionX + 275
});
const table = {
title: "Zápis koordinátora " + koordinatorName + " zo dna " + creationDate + ".",
divider: {
header: { disabled: false },
horizontal: { disabled: false, width: 0.5, opacity: 1 },
padding: 25,
columnSpacing: 20,
},
headers: [
{ label:"Názov", property: 'name', width: 70, renderer: null },
{ label:"Názov staveniska (stavba)", property: 'construction', width: 80, renderer: null },
{ label:"Vytvoril koordinátor BOZP", property: 'createdName', width: 80, renderer: null },
{ label:"Priorita", property: 'priority', width: 50, renderer: null },
{ label:"Dátum zistenia", property: 'date', width: 80, renderer: null },
{ label:"Zodpovedný za vyriešenie zistenia", property: 'responsible', width: 100, renderer: null },
{ label:"Miesto zistenia", property: 'placeOfDiscovery', width: 90, renderer: null },
],
datas: [
{
options: { fontSize: 10, separation: true},
name: problemName,
construction: constructionName,
createdName: koordinatorName,
priority: problemPriority,
date: creationDate,
responsible: responsible,
placeOfDiscovery: discoveryPlace,
},
],
};
doc.table(table, {
columnSpacing: 10,
padding: 10,
columnsSize: [200,220,135],
align: "center",
prepareHeader: () => doc.font("Helvetica-Bold").fontSize(8),
prepareRow: (row, indexColumn, indexRow, rectRow, rectCell) => {
const {x, y, width, height} = rectCell;
if(indexColumn === 0){
doc
.lineWidth(.5)
.moveTo(x, y)
.lineTo(x, y + height)
.stroke();
}
doc
.lineWidth(.5)
.moveTo(x + width, y)
.lineTo(x + width, y + height)
.stroke();
doc.fontSize(8).fillColor('#292929');
},
});
const table2 = {
divider: {
header: { disabled: false },
horizontal: { disabled: false, width: 0.5, opacity: 1 },
padding: 25,
columnSpacing: 20,
},
headers: [
{ label:"Návrh na udelenie sankcie", property: 'sanction', width: 100, renderer: null },
{ label:"Pre spolocnost", property: 'forCompany', width: 100, renderer: null },
{ label:"Popis problému", property: 'text', width: 350, renderer: null},
],
datas: [
{
options: { fontSize: 10, separation: true},
sanction: 50,
forCompany: adressedFor,
text: problemText,
},
],
};
doc.table(table2, {
columnSpacing: 10,
padding: 10,
columnsSize: [200,220,135],
align: "center",
prepareHeader: () => doc.font("Helvetica-Bold").fontSize(8),
prepareRow: (row, indexColumn, indexRow, rectRow, rectCell) => {
const {x, y, width, height} = rectCell;
if(indexColumn === 0){
doc
.lineWidth(.5)
.moveTo(x, y)
.lineTo(x, y + height)
.stroke();
}
doc
.lineWidth(.5)
.moveTo(x + width, y)
.lineTo(x + width, y + height)
.stroke();
doc.fontSize(8).fillColor('#292929');
},
});
doc.end();
await highPriorityEmail(emailGroup);
})
.catch((err) => {
console.log(err);
res.status(500)
})
.then(() => {
res.status(200).send({
message: "Nedostatok bol úspešne vytvorený.",
});
})
} catch (err) {
console.log(err);
res.status(500);
}
},
Here is also new HighPriorityEmail() function, which now gets parameter.
function highPriorityEmail(emailGroup){
return new Promise((resolve, reject) => {
setTimeout(async () => {
const emailAdress = await getEmails(emailGroup);
let filePath = path.join(__dirname, `../../pdf/${problemName}_${creationDate}.pdf`);
let attachment = fs.readFileSync(filePath).toString("base64");
let fileName = `${problemName}_${creationDate}.pdf`;
if (problemPriority == "vysoká") {
const msg = {
to: emailAdress, // Change to your recipient
from: "someone#example.com"
subject: "Vytvorenie nového nedostatku: " + problemName,
html: `
Dobrý deň, <br>
<br>
dňa ${creationDate} bol vykonaný dozor koordinátora ${koordinatorName}. <br>
Boli zistené nedostatky s vysokou prioritou, ktoré sú priložené v prílohe tohoto emailu.
<br>
`,
attachments: [
{
content: attachment,
filename: fileName,
type:'application/pdf'
},
],
};
sgMail
.send(msg)
.then(() => {
console.log("Email sent");
})
.catch((error) => {
console.error(error);
});
Case.update(
{ wasSended: 1 },
{ returning: true, where: { caseName: problemName } }
);
}
resolve();
}, 1000)
});
};
And finally here is getEmails() function.
async function getEmails (emailGroup){
const groupResponse = await MailingListGroup.findAll({ where: { mailingListGroup: emailGroup }})
let gropudId = JSON.stringify(groupResponse[0].id);
const emailsResponse = await MailingListEmails.findAll({ where: { mailingListGroup: gropudId }})
const emails = [];
for(let i=0; i<emailsResponse.length; i++){
emails.push(emailsResponse[i].email);
}
return emails;
}
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
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(), {...});
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.
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');
});