Friday, November 9, 2007

Caclulating with values from siblings

I have a form where I want to be able to specify a percentage value. I also want to make sure that the total value of all siblings is not more than 100 and to calculate the value based on teh value in the parent document.

In this case it was Operatives for a Deal. My structure is
Deal $20,0000
Operative 1 : 25%
Operative 2: 55%
Operative 3: 20%

What I want to prevent is somebody coming along and changing the value of Operative 3to 30%.
To do this i include this code in the forms onLoad event:

//----------------------------------------------------------
checkPercentage = function() {
//----------------------------------------------------------
var f = crmForm.all;
var retVal = false;


//setup some vars to use in constructing the formula and storing the values
var entityForList = 'new_listingoperative';
var attribForFilter = 'new_dealid' ;
var idToFetch = f.new_dealid.DataValue[0].id+ '' ;
var attribToReturn = 'new_percentage';
var resultXml = getattribByLookup( entityForList, attribForFilter, idToFetch, attribToReturn );
var totalPerc = 0.00;


if ( resultXml.selectSingleNode("//RetrieveMultipleResult") != null ) {
var node = resultXml.selectSingleNode("//RetrieveMultipleResult");
var percNodes = node.selectNodes("//new_percentage");
var idNodes = node.selectNodes("//new_listingoperativeid");

// if this is a new & unsaved form add it to the total before cycling through the return list
var totalPerc = 0.00;
if ( crmForm.FormType == 1 ) { totalPerc += f.new_percentage.DataValue; }

//this list will only include saved forms
for ( i = 0; i < percNodes.length; i++ ) {
if( isCurrentRecord( idNodes[ i ].text ) ) {
totalPerc += f.new_percentage.DataValue;
} else {
totalPerc += parseFloat( percNodes[ i ].text );
}
}
}

if( totalPerc <= 100.00 ) { retVal = true; }
return retVal ;

};

And this code in the fields onChange event
if( !checkPercentage() ) {
alert( 'ERROR: The total of all percentage amounts must be no greater than 100%');
crmForm.all.new_percentage.DataValue = 0.00;
}

No comments: