I face a big problem in CRM there is no calculated field based on other fields
the main problem alot of code to done
I make this method which allow me to make calculated field based on formula
this formula contains the names of the fields which this formula depending on it.
if the any fields that exist in the formula changes it will change the total field automatic.
var LoadedArray = new Array();
function CalculateField(fieldName, equation) {
// debugger;
var MainEquation = '';
MainEquation = equation;
var tempEquation = equation.CustomReplace("\*", ',').CustomReplace('/', ',').CustomReplace('+', ',').CustomReplace('-', ',');
tempEquation = tempEquation.CustomReplace('.', '').CustomReplace('0', '').CustomReplace('1', '').CustomReplace('2', '');
tempEquation = tempEquation.CustomReplace('3', '').CustomReplace('4', '').CustomReplace('5', '').CustomReplace('6', '');
tempEquation = tempEquation.CustomReplace('7', '').CustomReplace('8', '').CustomReplace('9', '');
var controls = tempEquation.split(',');
for (var i = 0; i < controls.length; i++) {
if (controls[i] == '' || controls[i] == null) continue;
var attribute = GetAttribute(controls[i]);
if (LoadedArray[fieldName] == undefined) {
var tempFunc = function () {
CalculateField(fieldName, equation);
};
//attribute.addOnChange(tempFunc);
Xrm.Page.data.entity.attributes.get(controls[i]).addOnChange(tempFunc);
}
var value = GetValueAttribute(controls[i]);
if (value == undefined) value = 0;
MainEquation = MainEquation.replace(controls[i], value);
}
SetValueAttribute(fieldName, eval(MainEquation));
ChangeFieldBackGround(fieldName, 'yellow');
SetEnabledState(fieldName, true);
if (LoadedArray[fieldName] == undefined) {
var tempDisableFunc = function () {
SetEnabledState(fieldName, false);
}
Xrm.Page.data.entity.addOnSave(tempDisableFunc);
}
LoadedArray[fieldName] = 1;
}
function SetEnabledState(controlName, value) {
var AddressType = Xrm.Page.ui.controls.get(controlName);
AddressType.setDisabled(value);
}
function ChangeFieldBackGround(fieldname, color) {
//crmForm.all[fieldname].style.backgroundColor = color;
var controles = document.getElementById(fieldname).parentNode.parentNode.getElementsByTagName('input');
for (var i = 0; i < controles.length; i++) {
controles[i].style.backgroundColor = color;
}
}
An Example for calling this Method
CalculateField('new_totalamount','0.5*new_price*new_quantity');