-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathdt-custom.js
445 lines (421 loc) · 16.1 KB
/
dt-custom.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
var mdataArray = [];
var EditRowData = [];
var ColumnData;
var table;
var isEditAllState = false;
var defaultcol = "";
var apiUrl = 'https://dtexample10.000webhostapp.com/api/';//Url for Server API
var backupApiUrl = 'https://dtexample10.000webhostapp.com/api/';//Url for Server API
var GetTableMetaApiEndpoint = 'gettablemeta.php';//Endpoint returning Table Metadata
var GetTableDataApiEndpoint = 'gettabledata.php';//Endpoint processing and return Table Data
var UpdateRowDataApiEndpoint = 'update.php';//Endpoint processing update request
var InsertRowDataApiEndpoint = 'create.php';//Endpoint processing insert request
var DeleteRowDataApiEndpoint = 'delete.php';//Endpoint processing delete request
//get Table and Columns properties
function getTableMeta() {
$.ajax({
type: 'GET',
url: apiUrl + GetTableMetaApiEndpoint,
success: function (data) {
console.log(data);
ColumnData = data.Column;
//Below for Expand Row
if (data.hasOwnProperty('Expandable') && data.Expandable == true) {
$('#dtexample thead tr:first-child').append($('<th>', {
text: 'Expand'
}));
$('#dtexample thead tr:nth-child(2)').append($('<th>', {
text: ''
}));
mdataArray.push({ defaultContent: '<img src="./Icons/openview.png" style="width:28px" />', class: 'details-control' });
InitializeFormatter();
if (data.Insertable == true) {
$('#dtexample tfoot tr:first-child').append($('<td></td>'));
}
}
//End for Expand Row
$.each(data.Column, function (index, element) {
$('#dtexample thead tr:first-child').append($('<th>', {
text: element.Name
}));
//insert
if (data.Insertable == true) {
if (element.Editable == true) {
$('#dtexample tfoot tr:first-child').append($('<td><input class="' + element.Name + 'Add" style="width: 99% " type="text" /></td>'
));
} else {
$('#dtexample tfoot tr:first-child').append($('<td></td>'
));
}
}
//search
if (element.Searchable == true)
$('#dtexample thead tr:nth-child(2)').append($('<th>', {
text: element.Name
}));
else $('#dtexample thead tr:nth-child(2)').append($('<th>', {
text: ''
}));
mdataArray.push({ mData: element.Name, class: element.Name });
});
if (data.Deletable == true) {
$('#dtexample thead tr:first-child').append($('<th>', {
text: 'Delete'
}));
$('#dtexample thead tr:nth-child(2)').append($('<th>', {
text: ''
}));
mdataArray.push({ defaultContent: '<span class="deleteBtn"><img src="./Icons/delete.png" style="width:28px" /></span>', class: 'DeleteRow' });
}
if (data.Insertable == true) {
$('#dtexample tfoot tr:first-child').append($('<td><span class="insertBtn"><img src="./Icons/add.png" style="width:28px" /></span></td>'
));
}
defaultcol = data.Column[0].Name;
//once table headers and table data property set, initialize DT
initializeDataTable();
},
error: function (xhr, status, error) {
if (apiUrl != backupApiUrl) {
apiUrl = backupApiUrl;
getTableMeta();
}
},
});
}
$(document).ready(function () {
getTableMeta();
});
$(document).keyup(function (e) {
if (e.keyCode == 27)
if (isEditAllState) {
CancelEditAll();
isEditAllState = false;
} else
cancelBtn();
});
function initializeDataTable() {
//put Input textbox for filtering
$('#dtexample thead tr:nth-child(2) th').each(function () {
var title = $(this).text();
if (title != '')
$(this).html('<input type="text" class="sorthandle" style="width:100%;" />');
});
//don't sort when user clicks on input textbox to type for filter
$('#dtexample').find('thead th').click(function (event) {
if ($(event.target).hasClass('sorthandle')) {
event.stopImmediatePropagation()
}
});
table = $('#dtexample').DataTable({
"ajax": {
"url": apiUrl + GetTableDataApiEndpoint,
"type": "POST",
data: function (data) {
editIndexTable = -1;
var colname;
var sort = data.order[0].column;
if (!data['columns'][sort]['data'] == '')
colname = data['columns'][sort]['data'] + ' ' + data.order[0].dir;
//in case no sorted col is there, sort by first col
else colname = defaultcol + " asc";
var colarr = [];
// colname = 'ID asc';
var colfilter, col;
var arr = {
'draw': data.draw, 'length': data.length,
'sort': colname, 'start': data.start, 'search': data.search.value
};
//add each column as formdata key/value for filtering
data['columns'].forEach(function (items, index) {
col = data['columns'][index]['data'];
colfilter = data['columns'][index]['search']['value'];
arr[col] = colfilter;
});
return arr;
}
},
"lengthMenu": [10, 50, 100], "searching": true,
//rowId required when doing update, can put any unique value for each row instead of ID
rowId: 'ID',
dom: '<"toolbar">frtip',
initComplete: function () {
$("div.toolbar").html('<a href="#" style="margin: 5px" class="btn btn-info btn-secondary" id="editallbtn" onclick="EditAll()">Edit All</a>' +
'<a href="#" style="margin: 5px" class="btn btn-info btn-secondary" id="deleteallbtn" onclick="deleteAllRows()">Delete All</a>' +
'<a href="#" class="btn btn-info btn-secondary" style="display: none;margin: 5px" id="saveallbtn" onclick="SaveAll()">Save</a>'
+ '<a href="#" class="btn btn-info btn-secondary" style="display: none;margin: 5px" id="canceleditallbtn" onclick="CancelEditAll()">Cancel</a>');
},
serverSide: true, "processing": true,
aoColumns: mdataArray
});
//call search api when user types in filter input
table.columns().every(function () {
var that = this;
$('input', this.header()).on('keyup change', function () {
if (that.search() !== this.value) {
that.search(this.value).draw();
}
});
});
var onEditClickcls = '';
$.each(ColumnData, function (index, element) {
if (element.Editable == true) {
onEditClickcls += 'tr td.' + element.Name + ',';
}
});
onEditClickcls = onEditClickcls.substring(0, onEditClickcls.length - 1);
console.log(onEditClickcls);
$("#dtexample tbody").on('click', onEditClickcls, function (e) {
if ($(e.target).is('input') || $(e.target).is('img') || $(e.target).is('span.copyAll') || isEditAllState) {
e.preventDefault();
return;
}
RoweditMode($(this).parent());
});
//for delete button
$("#dtexample tbody").on('click', 'tr td span.deleteBtn', function (e) {
// RoweditMode($(this).parent().parent());
deleteRow(this.parentNode.parentNode);
});
//for insert button
$("#dtexample tfoot").on('click', 'tr td span.insertBtn', function (e) {
// RoweditMode($(this).parent().parent());
insertRowData(this.parentNode.parentNode);
});
$("#dtexample tbody").on('keyup', 'input.userinput', function (e) {
if (e.keyCode == 13) {
//Check if edit all state
if (isEditAllState) {
SaveAll();
} else {
updateRowData(this.parentNode.parentNode);
}
}
});
}
var editIndexTable = -1;
function RoweditMode(rowid) {
var prevRow;
var rowIndexVlaue = parseInt(rowid.attr("indexv"));
if (editIndexTable == -1) {
saveRowIntoArray(rowid);
rowid.attr("editState", "editState");
editIndexTable = rowid.rowIndex;
setEditStateValue(rowid, rowIndexVlaue + 2);
}
else {
prevRow = $("[editState=editState]");
prevRow.attr("editState", "");
rowid.attr("editState", "editState");
editIndexTable = rowIndexVlaue;
saveArrayIntoRow(prevRow);
saveRowIntoArray(rowid);
setEditStateValue(rowid, rowIndexVlaue + 2);
}
}
function setEditStateValue(td1, indexRow) {
for (var k in EditRowData) {
$($(td1).children('.' + k)[0]).html('<input value="' + EditRowData[k] + '" class="userinput" style="width: 99% " />');
}
}
function cancelBtn() {
var prevRow = $("[editState=editState]");
prevRow.attr("editState", "");
if (prevRow.length > 0) { saveArrayIntoRow($(prevRow)); }
editIndexTable = -1;
}
function saveRowIntoArray(cureentCells) {
$.each(ColumnData, function (index, element) {
if (element.Editable == true) {
var htmlVal = $($(cureentCells).children('.' + element.Name)[0]).html();
EditRowData[element.Name] = htmlVal;
}
});
}
function saveArrayIntoRow(cureentCells) {
for (var k in EditRowData) {
$($(cureentCells).children('.' + k)[0]).html(EditRowData[k]);
}
}
function updateRowData(currentCells) {
var table = $("#dtexample").DataTable();
var row = table.row(currentCells);
rowid = currentCells.getAttribute('id');
var UpdateRowData = [];
var aoColss = {}
$.each(ColumnData, function (index, element) {
if (element.Editable == true) {
aoColss[element.Name] = $($($(currentCells).children('.' + element.Name)).children('input')[0]).val();
}
});
aoColss['rowid'] = rowid;
UpdateRowData.push(aoColss);
UpdateData(UpdateRowData);
}
//Update
function UpdateData(jsonUpdate) {
$.ajax({
type: 'POST',
url: apiUrl + UpdateRowDataApiEndpoint,
data: JSON.stringify(jsonUpdate),
success: function (data) {
var table = $('#dtexample').DataTable();
table.draw('page');
}
});
}
//Edit All
var EditAllData = [];
function EditAll() {
cancelBtn();
$('#dtexample tbody tr').each(function () {
varrowid = this.getAttribute('id');
var that = this;
var EditDT = [];
$.each(ColumnData, function (index, element) {
if (element.Editable == true) {
var htmlVal = $($(that).children('.' + element.Name)[0]).html();
EditDT[element.Name] = htmlVal;
$($(that).children('.' + element.Name)[0]).html('<input value="' + htmlVal + '" class="userinput" style="width: 99% " />');
}
});
EditDT['rowid'] = varrowid;
EditAllData.push(EditDT);
});
$('#editallbtn').css('display', 'none');
$('#canceleditallbtn').css('display', 'inline-block');
$('#saveallbtn').css('display', 'inline-block');
isEditAllState = true;
}
function CancelEditAll() {
$('#dtexample tbody tr').each(function () {
varrowid = this.getAttribute('id');
var filterednames = EditAllData.filter(function (obj) {
return (obj['rowid'] == varrowid);
});
var that = this;
for (var k in filterednames[0]) {
$($(that).children('.' + k)[0]).html(filterednames[0][k]);
}
});
isEditAllState = false;
$('#editallbtn').css('display', 'inline-block');
$('#canceleditallbtn').css('display', 'none');
$('#saveallbtn').css('display', 'none');
}
function SaveAll() {
var UpdateRowData = [];
$('#dtexample tbody tr').each(function (indx, currentRow) {
rowid = this.getAttribute('id');
var aoColss = {}
$.each(ColumnData, function (index, element) {
if (element.Editable == true) {
aoColss[element.Name] = $($($(currentRow).children('.' + element.Name)).children('input')[0]).val();
}
});
aoColss['rowid'] = rowid;
UpdateRowData.push(aoColss);
});
UpdateData(UpdateRowData);
isEditAllState = false;
$('#editallbtn').css('display', 'inline-block');
$('#canceleditallbtn').css('display', 'none');
$('#saveallbtn').css('display', 'none');
}
//Delete current row
function deleteRow(currentCells) {
var table = $("#dtexample").DataTable();
rowid = currentCells.getAttribute('id');
jsonDelete = [{ rowid: rowid }];
deleteData(jsonDelete);
}
//delete all
function deleteAllRows() {
if (confirm("Are you sure you want to delete filtered rows?")) {
jsonDelete = [];
$('#dtexample tbody tr').each(function () {
varrowid = this.getAttribute('id');
// var that = this;
// var table = $("#dtexample").DataTable();
//var row = table.row(currentCells);
// rowid = currentCells.getAttribute('id');
jsonDelete.push({ rowid: varrowid });
});
deleteData(jsonDelete);
}
}
//delete
function deleteData(jsonDelete) {
$.ajax({
type: 'POST',
url: apiUrl + DeleteRowDataApiEndpoint,
data: JSON.stringify(jsonDelete),
success: function (data) {
var table = $('#dtexample').DataTable();
table.draw('page');
}
});
}
//insert row
function insertRowData(currentCells) {
var table = $("#dtexample").DataTable();
var row = table.row(currentCells);
var InsertRowData = [];
console.log(currentCells);
$.each(ColumnData, function (index, element) {
InsertRowData.push({
'pname': element.Name, 'pvalue': $($($(currentCells).children('.' + element.Name)).children('input.' + element.Name + 'Add')[0]).val()
});
});
var parameter = "";
for (i = 0; i < InsertRowData.length; i++) {
if (i == InsertRowData.length - 1)
parameter = parameter + InsertRowData[i].pname + "=" + InsertRowData[i].pvalue;
else
parameter = parameter + InsertRowData[i].pname + "=" + InsertRowData[i].pvalue + "&";
}
$.ajax({
type: 'POST',
url: apiUrl + InsertRowDataApiEndpoint,
data: parameter,
success: function (data) {
var table = $('#dtexample').DataTable();
table.draw('page');
}
});
}
function InitializeFormatter() {
$('#dtexample tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
tr.removeClass();
// This row is already open - close it
row.child.hide();
}
else {
// Open this row
tr.addClass("thisRowShown");
var histrows = format(row.data());
row.child($(histrows)).show();
}
});
}
function format(d) {
// `d` is the original data object for the row
var b = '<tr class="gridlistCss">' +
'<td></td>' +
'<td class="dt-center">' + d.ID + '</td>' +
'<td class="dt-center">' + d.ORD_NUM + '</td>' +
'<td class="dt-center">' + d.ORD_AMOUNT + '</td>' +
'<td class="dt-center">' + d.ADVANCE_AMOUNT + '</td>' +
'<td class="dt-center">' + d.ORD_DATE + '</td>' +
'<td class="dt-center">' + d.AGENT_CODE + '</td>' +
'<td class="dt-center">' + d.CUST_CODE + '</td>' +
'<td class="dt-center">' + d.ORD_DESCRIPTION + '</td>' +
'<td class="dt-center"></td>' +
'</tr>';
var final = b;//comment this to expand with div
//final="<div><span>One span in DIV"+d.ORD_NUM+"</span></div>";//comment this to show data in Table format
return final;
}