Form Update Dataset using additional calculated values

I have a form with two datasets which are connected by a common field. One dataset is shown as a dropdown on the form and I want to take the value from the dropdown and set the value of a field on the other dataset when a new record is created.


The regions collection looks like this:-


When a new region is created I want the new row in the collection to take the countryName from the dropdown value and the code to be the next number in the sequence. I have a function which will calculate the extra data (at least i hope it does:)) :-

function regionsBeforeSave(){

let myNewCode = 0; 
console.log("beforeInsert - get new code"); 
wixData.query("regions").descending("code").find() 
	.then((results) =>{ 
		let items = results.items; 
		myNewCode = items[0]["code"] + 1; 
	}); 

console.log("beforeInsert - add code, country" + myNewCode); 
$w("#regionsDataset").setFieldValues({ 
	"code": myNewCode, 
	"countryCode": $w("#countryDd").value 
});	 

}

and have added the following line to the page onready

$w(“#regionsDataset”).onBeforeSave(regionsBeforeSave);

I was hoping this would create an event which would fire when the save button is clicked but it actually is executed immediately on entering the page, and i get the error:-

new operation failed: DatasetError: Operation cancelled by user code. DatasetError: There is no current item

Any help with this would be appreciated.

1 Like

Were you able to get this functioning correctly for you?
I have a similar requirement.