- Configure business object ( Ex: Country )
- Load data into business object
- Add a download button.
- On button click call rest API to fetch all data in business object using action chain.
- Create CSV content as blob
- Download blob file using JavaScript function
Sample BO data
Id | Country Name | Country Short Code |
---|---|---|
21 | Afghanistan | AF |
22 | Albania | AL |
23 | Algeria | DZ |
24 | American Samoa | AS |
25 | Andorra | AD |
26 | Angola | AO |
27 | Anguilla | AI |
<oj-button label="Download" on-oj-action="[[$listeners.buttonAction]]">
<span class="oj-ux-ico-download" slot="startIcon"></span>
</oj-button>
Action chain code for calling Javascript function
{
"description": "",
"root": "callFunctionDownloadDataFromBO",
"actions": {
"callFunctionDownloadDataFromBO": {
"module": "vb/action/builtin/callModuleFunctionAction",
"parameters": {
"module": "[[ $functions ]]",
"functionName": "downloadDataFromBO"
}
}
},
"variables": {}
}
JavaScript function code to call business object rest API and download as csv
define(['vb/helpers/rest'], (Rest) => {
'use strict';
class PageModule {
getLineItems(prevItems) {
if (prevItems == undefined || prevItems == null) {
prevItems = [];
}
let endpointurl = "businessObjects/getall_Country";
let queryString = "id is not null";
var pageModuleVar = this;
return new Promise(function (resolve, reject) {
var ep = Rest.get(endpointurl);
ep.parameters({
"q": queryString,
"onlyData": true,
limit: 500,
offset: prevItems.length,
"orderBy": "id:asc"
});
ep.fetch().then(function (result) {
if (result.response.ok) {
var currentItems = prevItems.concat(result.body.items);
if (result.body.hasMore == true) {
resolve(pageModuleVar.getLineItems(currentItems));
}
else {
resolve(currentItems);
}
}
else {
resolve([]);
}
});
});
}
async downloadDataFromBO() {
let lineItems = [];
lineItems = await this.getLineItems(lineItems);
let fieldNames = [
{
"display": "Id",
"fieldName": "id"
}, {
"display": "Country Name",
"fieldName": "countryName"
}, {
"display": "Country Code",
"fieldName": "countryShortCode"
}
];
let headerLine = fieldNames.map(function (fieldObj) {
return fieldObj.display;
}).join(",");
let csvData = headerLine;
for (let i = 0; i < lineItems.length; i++) {
csvData += "\r\n";
let csvRow = "";
for (let j = 0; j < fieldNames.length; j++) {
csvRow += '"' + lineItems[i][fieldNames[j].fieldName] + '"' + ",";
}
csvData += csvRow;
}
const blob = new Blob([csvData], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.setAttribute('href', url);
a.setAttribute('download', 'download.csv');
a.click();
}
}
return PageModule;
});