diff --git a/public/assets/js/csv_export.js b/public/assets/js/csv_export.js new file mode 100644 index 00000000..6910ba54 --- /dev/null +++ b/public/assets/js/csv_export.js @@ -0,0 +1,74 @@ +$(function() { + // export table to csv + $(document).on('click', '[data-export-csv]', async function(e) { + const el = e.target.closest('[data-export-csv]'); + const oldLabel = el.innerHTML; + + // set loading status + el.disabled = true; + el.innerHTML = 'Exporting...'; + + const formData = new FormData(); + + formData.append('datatable[pagination][page]', 1); + formData.append('datatable[pagination][perpage]', 10000000); + + // get all rows + const response = await fetch(el.dataset.url, { + method: el.dataset.method, + body: formData, + }); + + const result = await response.json(); + + if (response.status === 200) { + // empty set returned + if (parseInt(result.meta.total) === 0) { + swal({ + title: 'Whoops', + html: 'No data to export!', + type: 'warning', + }); + } + + // build csv data + const csvRows = []; + const fieldList = el.dataset.fields.split(','); + csvRows.push(el.dataset.headers); + + result.data.forEach((row) => { + const fieldData = []; + fieldList.forEach((field) => { + fieldData.push('"' + row[field] + '"'); + }); + + csvRows.push(fieldData.join(',')); + }); + + const csvData = csvRows.join('\n'); + + // build the csv file + const csvFile = new Blob([csvData], { + type: 'text/csv', + }); + + // create a link to the file and download it + const url = window.URL.createObjectURL(csvFile); + const a = document.createElement('a'); + a.href = url; + a.download = el.dataset.filename + '.csv'; + a.click(); + } else { + // something went wrong on the server + swal({ + title: 'Whoops', + html: 'An error has occurred while retrieving data.', + type: 'error', + }); + } + + // remove loading status + el.disabled = false; + el.innerHTML = oldLabel; + }); +}); \ No newline at end of file diff --git a/templates/vehicle-manufacturer/list.html.twig b/templates/vehicle-manufacturer/list.html.twig index dc5a9b1c..518afdb7 100644 --- a/templates/vehicle-manufacturer/list.html.twig +++ b/templates/vehicle-manufacturer/list.html.twig @@ -33,6 +33,13 @@