Vorbly <Code>
CODING MADE EASY WITH VORBLY
WIX TABLE SUM VALUE FROM DATABASE
Need to create summary table with sum values from a database? This tutorial will show you how to sum values and numbers from your database and input the information in a summary table using Wix Code. We will provide you with the webpage elements and sample codes required to implement this feature.
THE DEMO
THE ELEMENTS
The Page
Wix Table: #table1
The Database
Create a database Expenses.
Recommended fields:
-
Month ID: month
-
Expense Type ID: type
-
Expense Amount ID: amount
THE CODE
Page Code
import wixData from 'wix-data';
import {monthSort} from 'public/utils';
$w.onReady(function () {
$w("#table1").columns = [{
"id": "col1",
"dataPath": "month",
"label": "Month",
"type": "string"
},
{
"id": "col2",
"dataPath": "total",
"label": "Total Expenses",
"visible": true,
"type": "number"
}
];
wixData.query("Expenses")
.ascending("month")
.limit(1000) // include a limit if you have more than 50 items
.find()
.then((result) => {
const months = result.items.map(x => x.month)
.filter((obj, index, self) => index === self.indexOf(obj))
.sort(monthSort);
const aggregated = months.map(x => {
return {
month: x,
total: result.items.filter(obj => obj.month === x)
.map(z => z.amount)
.reduce((sum, current) => sum + current)
};
});
$w("#table1").rows = aggregated;
console.log($w("#table1").rows);
});
});
Public Code
// months.js //
const months = [ "January", "February", "March", "April",
"May", "June", "July", "August", "September", "October", "November", "December" ];
export function monthSort(a, b) {
return months.indexOf(a) - months.indexOf(b);
}
COMMENTS
I'm a paragraph. Click here to add your own text and edit me. It's easy.