Java Script:
In this Blog we will see How to Calculate Current/Related Year YTD based on the salary month by using javascript.
Firstly we need to create three fields Year, Amount(Whole Number), and YTD(whole Number).
Next change the below code according to your fields names.
function UpdateYTDValuesBasedOnYear() {
// Define the API context based on the environment
var apiContext = (typeof Xrm !== “undefined”) ? Xrm : parent.Xrm;
// Object to store totals grouped by year
var yearTotals = {};
// Retrieve all records from the “uma_income” entity
apiContext.WebApi.retrieveMultipleRecords(“uma_income”, “?$select=uma_incomeid,uma_amount,uma_year”).then(
function success(results) {
console.log(“Retrieved records:”, results);
// Loop through the retrieved records to calculate YTD totals by year
results.entities.forEach((record) => {
var uma_year = parseInt(record[“uma_year”], 10);
var uma_amount = parseInt(record[“uma_amount”], 10);
// Validate year and amount fields
if (!isNaN(uma_year) && !isNaN(uma_amount)) {
// Initialize the year in yearTotals if not already present
if (!yearTotals[uma_year]) {
yearTotals[uma_year] = 0;
}
// Add the amount to the respective year’s total
yearTotals[uma_year] += uma_amount;
}
});
// Log the calculated YTD totals for debugging
console.log(“Yearly Totals:”, yearTotals);
// Loop through the records again to update the YTD field
results.entities.forEach((record) => {
var uma_year = parseInt(record[“uma_year”], 10);
// Ensure the record has a valid year
if (!isNaN(uma_year) && yearTotals[uma_year] !== undefined) {
var ytdTotal = yearTotals[uma_year];
// Update the uma_ytd field for the current record
apiContext.WebApi.updateRecord(“uma_income”, record[“uma_incomeid”], {
uma_ytd: ytdTotal
}).then(
function success(updateResult) {
console.log(“Updated record:”, record[“uma_incomeid”], “with YTD:”, ytdTotal);
},
function error(updateError) {
console.error(“Error updating record:”, updateError.message);
}
);
}
});
},
function error(error) {
console.error(“Error retrieving records:”, error.message);
}
);
}
Next, create a web resource.
My webresource name is Income.
Enter your name, type and code.
Next add this library to your form.
Next add that webresource to your formproperties.
and add that code on form Onchange property.
Next, you can save and publish your changes. and test it once.
The below screen represents the total YTD in 2023 year.
The above screen shot represents the total YTD in 2025.
For any Help or Queries Contact us on info@crmonce.com or +91 9493926112.