I am attempting to setup a dynamic page, where each page contains a review of a food recipe. Each review is has 1 - 5 points awarded on different criteria. This is displayed on the page via connecting several cells of data to review stars. However, I want to create an “Overall” review, which is the average of the other data. I have not found a way to have the data auto calculate in the database, so I am trying to use Wix Code to do it on the actual page. I am struggling to find a way of actually assigning the value to the specific property. I am not very good at this Wix Code thing yet, so I would appreciate your help. Below has been my best shot at it (at least this one is not throwing errors, though not working either).
$w.onReady(function () {
//TODO: write your page related code here...
$w("#dynamicDataset").onReady(() => {
let item = $w("#dynamicDataset").getCurrentItem();
let sum = 0.0;
let count = 0.0;
let FieldToUse = ['quality', 'presentation', 'value', 'technique', 'service', 'atmosphere']
for (let key in item){
if (FieldToUse.includes(key)){
sum += item[key].value;
count += 1.0;
}
}
$w('#dynamicDataset').setFieldValue({'overall':sum/count})
})
});
I suggest you to use the hook function beforeInsert() on your database.
Add an “overall” field to your database and in the hook function add the calculation code,
as a result, each time you add a new item, the overall field will be automatically calculated.
Pay attention this function is written in the backend as data.js.
*I suggest you to change the fields properties that are going to be calculate to a Number .
In order to export this function go to your database-> at the top of the right side you will see the Hooks tab.
However, neither the code listed, or any seemingly logical variation, such as the below, seem to perform anything at all. The error on the load pages is that the value for “overall” is still null. I gave up on using beforeInsert() because this actually looked like it was dependent on user interaction on the site rather than happening before/while loading. Any other ideas?
export function Reviews_beforeInsert(item, context) {
let tmpitem = item;
let sum = 0.0;
let count = 0.0;
let FieldToUse = ['quality', 'presentation', 'value', 'technique', 'service', 'atmosphere'];
for (let key in item){
if (FieldToUse.includes(key)){
sum += item[key];
count += 1.0;
}
}
tmpitem.overall = sum/count;
return tmpitem;
}