Solved

Get Related Records & Tally Total CRM 2011

Posted on 2011-03-25
2
1,773 Views
Last Modified: 2012-05-11
I have created two custom entities (cgizmo_donation & cgizmo_inkinddonation) which I'm trying to get to work like the salesorder and product entities. Basically, the cgizmo_donation entity is an "order" page and the cgizmo_inkinddonation is the "products" page.

When a donation record is created, items are added via a relationship to the cgizmo_inkinddonation entity. What I need is a function that fetchs all the items from the related cgizmo_inkinddonation entity, tallys the total amounts, and saves this to a field on the cgizmo_donation entity.

The attached code does this, but for some reason, the tally isn't saved with the donation record - unless the function is re-run, which doesn't work because I need to pull this information into another entity. It's very important that the totals are saved to the donation record, without needing to call the function again.

The screenshot shows the relevant sections of the form. The totals tallied from related records needs to be saved to the field named "In-Kind Amount".

I've tried everything I could think of, but I can't get this to work.

Any help would be appreciated.
/// <reference path="../../IntelliSense/XrmPage-vsdoc.js" />
var ID_OF_LOOKUP_ON_DONATIONITEM = "cgizmo_donation",
	THIS_ENTITY_PRIMARY_KEY_ATTRIBUTE = 'cgizmo_donationid';

function executeOnLoad() {

    attachEvents();
    setupForm();

    if (crmForm.FormType == FormType.Update) {
        updateDonationStatistics();
        calculateTotal();
    }
}

function setupForm() {
    //hide name
    var attribute = Xrm.Page.data.entity.attributes.get("cgizmo_name");
    if (attribute != null) {
        var control = attribute.controls.get(0);
        if (control != null && control.getVisible()) {
            control.setVisible(false);
        }
    }
    //if collected, disable form.
    var statuscode = crmForm.all.statuscode;
    if (statuscode && statuscode.SelectedText == "Collected") {
        disableForm();
    }
}

function attachEvents() {

}

function disableForm() {
    Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
        if (attribute.getName() != "statuscode") {
            var control = attribute.controls.get(0);
            if (control != null && !control.getDisabled() && control.getVisible()) {
                control.setDisabled(true);
            }
        }
    });
}

function recalculate() {
	updateDonationStatistics();
	calculateTotal();
}

function executeOnSave() {

    var name = getAttribute("cgizmo_name"),
		constituent = getAttribute("cgizmo_contact"),
		member = getAttribute("cgizmo_account"),
		campaign = getAttribute("cgizmo_campaign"),
		date = getAttribute("cgizmo_donationdate"),
		pledge = getAttribute("cgizmo_pledge"),
		program = getAttribute("cgizmo_program"),
		amount = getAttribute("cgizmo_amount");

    var currentName = '';
    if (date) {
        currentName += date.format('MM/dd/yyyy');
    }
    if (constituent && constituent[0].name) {
        currentName += " " + constituent[0].name;
    }
    if (member && member[0]) {
        currentName += " " + member[0].name;
    }
    if (pledge && pledge[0]) {
        currentName += " " + pledge[0].name;
    }
    if (program && program[0]) {
        currentName += " " + program[0].name;
    }
    if (campaign && campaign[0]) {
        currentName += " " + campaign[0].name;
    }
    if (amount) {
        currentName += " " + formatCurrency(amount);
    }
    setAttribute("cgizmo_name", currentName);
}

function calculateTotal() {
	var totalCash = Xrm.Page.data.entity.attributes.get('cgizmo_cashamount').getValue();
	var totalInKind = Xrm.Page.data.entity.attributes.get('cgizmo_inkindamount').getValue();
	var totalBenefits = Xrm.Page.data.entity.attributes.get('cgizmo_totalbenefits').getValue();
	var totalContribution = totalCash + totalInKind;
	var totalDeductible = totalContribution - totalBenefits;
	var totalDonation = totalContribution;

	Xrm.Page.data.entity.attributes.get('cgizmo_deductibleamount').setValue(totalDeductible);
	Xrm.Page.data.entity.attributes.get('cgizmo_amount').setValue(totalDonation);
}

function updateDonationStatistics() {
	var stats = getDonationStatistics(crmForm.ObjectId);
	if (stats != null) {
		stats = populateDonationStatistics(stats);
	}
}

function getDonationStatistics(parentId) {
	var STATUSCODE_INACTIVE_COLLECTED = 973710005,
		STATUSCODE_ACTIVE_COLLECTED = 973710002;

	if (!Utils.Guid.isValid(parentId)) {
		//log("parentId is not a valid Guid.");
		return null;
	}

    var inkindTransactions = 0, 
        inkindTransactionAmt = 0;

	var today = new Date(),
		donations = getDonationRecords(crmForm.ObjectId),
		atLeastOneDonation = false;

	$.each(donations, function () {
		if (this.statuscode.DataValue != STATUSCODE_ACTIVE_COLLECTED &&
		this.statuscode.DataValue != STATUSCODE_INACTIVE_COLLECTED) {
			return;
		}

		atLeastOneDonation = true;

		inkindTransactionAmt += this.cgizmo_amount.DataValue;
		inkindTransactions++;

	});

	return !atLeastOneDonation ? {
	    cgizmo_inkindtransactions: inkindTransactions,
        cgizmo_inkindamount: inkindTransactionAmt
	} : {
        cgizmo_inkindtransactions: inkindTransactions,
		cgizmo_inkindamount: inkindTransactionAmt
	};

}

function getDonationRecords(parentId) {
	if (!Utils.Guid.isValid(parentId)) {
		log("parentId is not a valid Guid.");
	}

	var conditions = [
		  new CrmService.Condition(ID_OF_LOOKUP_ON_DONATIONITEM, "Equal", parentId)
	];

	var records = CrmService.retrieveMultiple("cgizmo_inkinddonation", conditions,
		"And", ["cgizmo_amount", "statuscode"]);

	//log(records);
	return records;
}

function populateDonationStatistics(stats) {

	var regExp = /_related_id$/;

	$.each(stats, function (fieldId, value) {
		if (regExp.test(fieldId)) { return; }

		var field = document.getElementById(fieldId);
		if (field) {
			if (field.format == 'date') {
				field.DataValue = value === '' ? null : value.DataValue;
				stats[fieldId] = value === '' ? value : value.value;
			} else {
				field.DataValue = value === '' ? null : value;
				stats[fieldId] = value;
			}
		}
	});

	return stats;
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

function getAttribute(attributeName) {
    var value = Xrm.Page.data.entity.attributes.get(attributeName);
    if (value)
        value = value.getValue();
    return value;
}

function setAttribute(attributeName, value) {
    var attribute = Xrm.Page.data.entity.attributes.get(attributeName);
    if (attribute) {
        attribute.setValue(value);
        attribute.setSubmitMode("always");
    }
}

FormType = function () {
	return {
		Undefined: 0,
		Create: 1,
		Update: 2,
		ReadOnly: 3,
		Disabled: 4,
		QuickCreate: 5,
		BulkEdit: 6
	};
} ();

MetadataService = function () {

	// MetadataService Private Methods 
	var getEntityMetadataProperty = function (entityName, metadataProperty) {
		var xml = "";
		xml += "<?xml version='1.0' encoding='utf-8'?>";
		xml += "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">";
		xml += generateAuthenticationHeader();
		xml += "<soap:Body>";
		xml += "<Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>";
		xml += "<Request xsi:type='RetrieveEntityRequest'>";
		xml += "<MetadataId>00000000-0000-0000-0000-000000000000</MetadataId>";
		xml += "<EntityItems />";
		xml += String.format("<LogicalName>{0}</LogicalName>", entityName);
		xml += "<RetrieveAsIfPublished>false</RetrieveAsIfPublished>";
		xml += "</Request>";
		xml += "</Execute>";
		xml += "</soap:Body>";
		xml += "</soap:Envelope>";

		var responseXml = executeCRMMetadataServiceMethod(xml);

		if (Utils.isValue(responseXml)) {
			return getNodeValue(responseXml, metadataProperty);
		}
	};

	var generateAuthenticationHeader = function () {
		if (window.GenerateAuthenticationHeader) {
			return GenerateAuthenticationHeader();
		}
		else if (parent.window.GenerateAuthenticationHeader) {
			return parent.window.GenerateAuthenticationHeader();
		}
	};

	var executeCRMMetadataServiceMethod = function (xml) {
		if (Utils.isValue(Cache[xml])) {
			return Cache[xml];
		}

		var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		xmlHttp.open("POST", "/mscrmservices/2007/metadataservice.asmx", false);
		xmlHttp.setRequestHeader("Content-Type", "text/xml; charset-utf-8");
		xmlHttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
		xmlHttp.send(xml);

		var errorCount = xmlHttp.responseXml.selectNodes('//error').length;
		if (errorCount != 0) {
			var errorMessage = xmlHttp.responseXml.selectSingleNode('//description').nodeTypedValue;
		}
		else if (xmlHttp.status != 200) {
		}
		else {
			Cache[xml] = xmlHttp.responseXml;
			return xmlHttp.responseXml;
		}
	};

	var getNodeValue = function (tree, el) {
		var retVal = null;
		var e = null;
		e = tree.getElementsByTagName(el);

		if (e != null && e[0] != null) {
			retVal = e[0].firstChild.nodeValue;
		}

		// If nothing was found, look for a UserLocLabel inner tag, and try to get the value from there
		if (retVal == null) {
			e = e[0].getElementsByTagName("UserLocLabel");
			if (e != null && e[0] != null) {
				retVal = e[0].firstChild.firstChild.nodeValue;
			}
		}

		return retVal;
	};

	// MetadataService Public Methods 
	return {
		getEntityTypeCode: function (entityName) {
			var typeCode = parseInt(getEntityMetadataProperty(entityName, "ObjectTypeCode"), 10);
			if (!isNaN(typeCode)) {
				return typeCode;
			}
			return null;
		}
	};
} ();

CrmService = function () {
	var generateAuthenticationHeader = function () {
		if (window.GenerateAuthenticationHeader) {
			return GenerateAuthenticationHeader();
		}
		else if (parent.window.GenerateAuthenticationHeader) {
			return parent.window.GenerateAuthenticationHeader();
		}
		else if (opener && opener.GenerateAuthenticationHeader) {
			return opener.GenerateAuthenticationHeader();
		}
	};

	var executeCRMWebServiceMethod = function (methodName, xml) {
		var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		xmlHttp.open("POST", "/mscrmservices/2007/crmservice.asmx", false);
		xmlHttp.setRequestHeader("Content-Type", "text/xml; charset-utf-8");
		xmlHttp.setRequestHeader("SOAPAction", String.format("http://schemas.microsoft.com/crm/2007/WebServices/{0}", methodName));
		xmlHttp.send(xml);

		var errorCount = xmlHttp.responseXml.selectNodes('//error').length;
		if (errorCount != 0) {
			var errorMessage = xmlHttp.responseXml.selectSingleNode('//description').nodeTypedValue;
		}
		else if (xmlHttp.status != 200) {
		}
		else {
			return xmlHttp.responseXml;
		}
	};

	var getNodeValue = function (tree, el) {
		var retVal = null;
		var e = null;
		e = tree.getElementsByTagName(el);

		if (e != null && e[0] != null) {
			retVal = e[0].firstChild.nodeValue;
		}

		return retVal;
	};

	var deserializeBusinessEntityIntoObject = function (businessEntityXmlNode, fields) {
		var result = {};

		// Create a new property for each field passed in.  This way, if it's null and not
		// returned by CRM, we'll still have the property in the result object.
		for (var i = 0; i < fields.length; i++) {
			result[fields[i]] = { value: null, DataValue: null };
		}

		if (businessEntityXmlNode && businessEntityXmlNode.childNodes && businessEntityXmlNode.childNodes.length > 0) {
			for (var i = 0; i < businessEntityXmlNode.childNodes.length; i++) {
				var isDate = false;
				var isNumber = false;
				var isLookup = false;
				var isPicklist = false;

				var childNode = businessEntityXmlNode.childNodes[i];
				var fieldName = childNode.tagName.replace("q1:", "");
				var fieldValue = childNode.text;

				result[fieldName] = {};

				for (var j = 0; j < childNode.attributes.length; j++) {
					var attributeName = childNode.attributes[j].nodeName;
					var attributeValue = childNode.attributes[j].nodeValue;

					result[fieldName][attributeName] = attributeValue;

					if (attributeName == "date") {
						isDate = true;
					}
					else if (attributeName == "formattedvalue" && !isNaN(fieldValue)) {
						isNumber = true;
					}
					else if (attributeName == "dsc") {
						isLookup = true;
					}
					else if (attributeName == "name") {
						isPicklist = true;
					}
				}

				var formattedValue = fieldValue;
				if (isDate) {
					formattedValue = new Date(result[fieldName].date + " " + result[fieldName].time);
				}
				else if (isNumber) {
					formattedValue = parseFloat(formattedValue);
				}
				else if (isLookup) {
					formattedValue = {
						id: fieldValue,
						typename: "",
						name: result[fieldName].name
					};
				}
				else if (isPicklist) {
					formattedValue = parseInt(formattedValue);
				}

				result[fieldName].value = fieldValue;
				result[fieldName].DataValue = formattedValue;
			}
		}

		return result;
	};

	function Attribute(attribute, value, type) {
		this.attribute = attribute;
		this.value = value;
		this.type = type;
	};

	Attribute.prototype.toString = function () {
		if (this.type)
			return String.format("<{0} type=\"{1}\">{2}</{0}>", this.attribute, this.type, this.value.toString());
		else
			return String.format("<{0}>{1}</{0}>", this.attribute, this.value.toString());
	};

	// CrmService Public Methods
	return {
		Condition: function (attribute, operator, value) {
			return { attribute: attribute, operator: operator, value: value };
		},

		retrieveMultiple: function (entityName, queryConditions, filterOperator, params_fields) {
			var result = [];

			var authHeader = generateAuthenticationHeader();
			if (Utils.isNull(authHeader)) {
				return result;
			}

			var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
			xml += "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">";
			xml += authHeader;
			xml += "<soap:Body><RetrieveMultiple xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>";
			xml += "<query xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:QueryExpression'>";
			xml += String.format("<q1:EntityName>{0}</q1:EntityName>", entityName);
			xml += "<q1:ColumnSet xsi:type='q1:ColumnSet'><q1:Attributes>";

			var fields = Utils.getArgumentsAsArray(arguments, 3);
			for (var i = 0; i < fields.length; i++) {
				xml += String.format("<q1:Attribute>{0}</q1:Attribute>", fields[i]);
			}

			xml += "</q1:Attributes></q1:ColumnSet>";
			xml += "<q1:Distinct>false</q1:Distinct>";
			xml += String.format("<q1:Criteria><q1:FilterOperator>{0}</q1:FilterOperator><q1:Conditions>", filterOperator);

			var conditionsAsArray = Utils.isArray(queryConditions) ? queryConditions : [queryConditions];

			for (var i = 0; i < conditionsAsArray.length; i++) {
				var currentCondition = conditionsAsArray[i];

				xml += "<q1:Condition>";
				xml += String.format("<q1:AttributeName>{0}</q1:AttributeName>", currentCondition.attribute);
				xml += String.format("<q1:Operator>{0}</q1:Operator>", currentCondition.operator);
				if (Utils.isValue(currentCondition.value)) {
					var valuesAsArray = Utils.isArray(currentCondition.value) ? currentCondition.value : [currentCondition.value];
					xml += "<q1:Values>";
					for (var j = 0; j < valuesAsArray.length; j++) {
						xml += String.format("<q1:Value xsi:type='xsd:string'>{0}</q1:Value>", valuesAsArray[j]);
					}
					xml += "</q1:Values>";
				}
				xml += "</q1:Condition>";
			}

			xml += "</q1:Conditions></q1:Criteria></query></RetrieveMultiple></soap:Body></soap:Envelope>";

			var responseXml = executeCRMWebServiceMethod("RetrieveMultiple", xml);

			if (Utils.isValue(responseXml)) {
				var retrieveResultNodes = responseXml.getElementsByTagName("BusinessEntity");

				if (retrieveResultNodes) {
					for (var i = 0; i < retrieveResultNodes.length; i++) {
						result.push(deserializeBusinessEntityIntoObject(retrieveResultNodes[i], fields));
					}
				}
			}

			return result;
		}
	};
} ();

Utils = function () {
	// Utils Private Methods 
	var hasConstructor = function (o) {
		return o !== null & o !== undefined && o.constructor;
	};

	// Utils Public Methods 
	return {

		isNull: function (o) {
			return (o === null);
		},

		isUndefined: function (o) {
			return (o === undefined);
		},

		isNumber: function (o) {
			return (this.isValue(o) && hasConstructor(o) && o.constructor.toString().indexOf("Number") > 0);
		},

		isValue: function (o) {
			return (!this.isNull(o) && !this.isUndefined(o));
		},

		isArray: function (o) {
			return (this.isValue(o) && hasConstructor(o) && o.constructor.toString().indexOf("Array") > 0);
		},

		isString: function (o) {
			return (this.isValue(o) && hasConstructor(o) && o.constructor.toString().indexOf("String") > 0);
		},

		getArgumentsAsArray: function (args, startIndex) {
			// If startIndex is not a number, default it to 0
			if (!this.isNumber(startIndex)) {
				startIndex = 0;
			}

			var finalResults = [];
			for (var i = startIndex; i < args.length; i++) {
				if (this.isArray(args[i])) {
					var innerArrayResults = this.getArgumentsAsArray(args[i]);

					for (var j = 0; j < innerArrayResults.length; j++) {
						finalResults.push(innerArrayResults[j]);
					}
				}
				else {
					if (args[i] !== null) {
						finalResults.push(args[i]);
					}
				}
			}

			return finalResults;
		}
	};
} ();

Utils.Guid = function () {
	// Utils.Guid Public Methods 
	return {
		isValid: function (guid) {
			if (!Utils.isString(guid)) {
				return false;
			}

			var hasValidBrackets = (guid.indexOf("{") === -1 && guid.indexOf("}") === -1) ||
									(guid.indexOf("{") === 0 && guid.indexOf("}") === guid.length - 1);

			var guidRegEx = new RegExp(/\{?([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}?$/);

			return hasValidBrackets && guidRegEx.test(guid);
		}
	};
} ();

Cache = function () {
	return {};
} ();

Open in new window

DynamicsDonationSnip01.png
0
Comment
Question by:savetheorcas
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
2 Comments
 

Accepted Solution

by:
savetheorcas earned 0 total points
ID: 35217073
I solved the problem! Here's the code that works:

/// <reference path="../../IntelliSense/XrmPage-vsdoc.js" />
var ID_OF_LOOKUP_ON_DONATIONITEM = "cgizmo_donation",
	THIS_ENTITY_PRIMARY_KEY_ATTRIBUTE = 'cgizmo_donationid';

function executeOnLoad() {
    calculateTotal();
    attachEvents();
    setupForm();
}

function setupForm() {
    //hide name
    var attribute = Xrm.Page.data.entity.attributes.get("cgizmo_name");
    var date = getAttribute("cgizmo_donationdate");
    if (attribute != null) {
        var control = attribute.controls.get(0);
        if (control != null && control.getVisible()) {
            control.setVisible(false);
        }
    }
    //if collected, disable form.
    var statuscode = crmForm.all.statuscode;
    if (statuscode && statuscode.SelectedText == "Collected") {
        disableForm();
    }

    if (date == null) {
        var today = new Date();
        setAttribute("cgizmo_donationdate", today);
    }
}

function attachEvents() {

}

function disableForm() {
    Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
        if (attribute.getName() != "statuscode") {
            var control = attribute.controls.get(0);
            if (control != null && !control.getDisabled() && control.getVisible()) {
                control.setDisabled(true);
            }
        }
    });
}

function recalculate() {
    updateDonationStatistics();
    calculateTotal();
}

function executeOnSave() {

    updateDonationStatistics();
    calculateTotal();

    var name = getAttribute("cgizmo_name"),
		constituent = getAttribute("cgizmo_contact"),
		member = getAttribute("cgizmo_account"),
		campaign = getAttribute("cgizmo_campaign"),
		date = getAttribute("cgizmo_donationdate"),
		pledge = getAttribute("cgizmo_pledge"),
		program = getAttribute("cgizmo_program"),
		amount = getAttribute("cgizmo_amount"),
        inkind = getAttribute("cgizmo_inkindamount");

    var currentName = '';
    if (date) {
        currentName += date.format('MM/dd/yyyy');
    }
    if (constituent && constituent[0].name) {
        currentName += " " + constituent[0].name;
    }
    if (member && member[0]) {
        currentName += " " + member[0].name;
    }
    if (pledge && pledge[0]) {
        currentName += " " + pledge[0].name;
    }
    if (program && program[0]) {
        currentName += " " + program[0].name;
    }
    if (campaign && campaign[0]) {
        currentName += " " + campaign[0].name;
    }
    if (amount) {
        currentName += " " + formatCurrency(amount);
    }
    setAttribute("cgizmo_name", currentName);
    setAttribute("cgizmo_amount", amount);
}

function calculateTotal() {
    var totalCash = Xrm.Page.data.entity.attributes.get('cgizmo_cashamount').getValue();
    var totalInKind = Xrm.Page.data.entity.attributes.get('cgizmo_inkindamount').getValue();
    var totalBenefits = Xrm.Page.data.entity.attributes.get('cgizmo_totalbenefits').getValue();
    var totalContribution = totalCash + totalInKind;
    var totalDeductible = totalContribution - totalBenefits;
    var totalDonation = totalContribution;

    Xrm.Page.data.entity.attributes.get('cgizmo_deductibleamount').setValue(totalDeductible);
    Xrm.Page.data.entity.attributes.get('cgizmo_amount').setValue(totalDonation);
}

function updateDonationStatistics() {
    var stats = getDonationStatistics(crmForm.ObjectId);
    if (stats != null) {
        stats = populateDonationStatistics(stats);
    }
}

function getDonationStatistics(parentId) {
    var STATUSCODE_INACTIVE_COLLECTED = 973710005,
		STATUSCODE_ACTIVE_COLLECTED = 973710002;

    if (!Utils.Guid.isValid(parentId)) {
        //log("parentId is not a valid Guid.");
        return null;
    }

    var inkindTransactions = 0,
        inkindTransactionAmt = 0;

    var today = new Date(),
		donations = getDonationRecords(crmForm.ObjectId),
		atLeastOneDonation = false;

    $.each(donations, function () {
        if (this.statuscode.DataValue != STATUSCODE_ACTIVE_COLLECTED &&
		this.statuscode.DataValue != STATUSCODE_INACTIVE_COLLECTED) {
            return;
        }

        atLeastOneDonation = true;

        inkindTransactionAmt += this.cgizmo_amount.DataValue;
        inkindTransactions++;

    });


    var inkindamt = getAttribute("cgizmo_inkindamount");
    var inkindgifts = getAttribute("cgizmo_inkindtransactions");

    if (inkindamt != inkindTransactionAmt) {
        setAttribute("cgizmo_inkindamount", inkindTransactionAmt);
    } else {
        setAttribute("cgizmo_inkindamount", inkindamt);
    }

    if (inkindgifts != inkindTransactions) {
        setAttribute("cgizmo_inkindtransactions", inkindTransactions);
    } else {
        setAttribute("cgizmo_inkindtransactions", inkindgifts);
    }
}

function getDonationRecords(parentId) {
    if (!Utils.Guid.isValid(parentId)) {
        log("parentId is not a valid Guid.");
    }

    var conditions = [
		  new CrmService.Condition(ID_OF_LOOKUP_ON_DONATIONITEM, "Equal", parentId)
	];

    var records = CrmService.retrieveMultiple("cgizmo_inkinddonation", conditions,
		"And", ["cgizmo_amount", "statuscode"]);

    //log(records);
    return records;
}

function populateDonationStatistics(stats) {

    var regExp = /_related_id$/;

    $.each(stats, function (fieldId, value) {
        if (regExp.test(fieldId)) { return; }

        var field = document.getElementById(fieldId);
        if (field) {
            if (field.format == 'date') {
                field.DataValue = value === '' ? null : value.DataValue;
                stats[fieldId] = value === '' ? value : value.value;
            } else {
                field.DataValue = value === '' ? null : value;
                stats[fieldId] = value;
            }
        }
    });

    return stats;
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

function getAttribute(attributeName) {
    var value = Xrm.Page.data.entity.attributes.get(attributeName);
    if (value)
        value = value.getValue();
    return value;
}

function setAttribute(attributeName, value) {
    var attribute = Xrm.Page.data.entity.attributes.get(attributeName);
    if (attribute) {
        attribute.setValue(value);
        attribute.setSubmitMode("always");
    }
}

FormType = function () {
    return {
        Undefined: 0,
        Create: 1,
        Update: 2,
        ReadOnly: 3,
        Disabled: 4,
        QuickCreate: 5,
        BulkEdit: 6
    };
} ();

MetadataService = function () {

    // MetadataService Private Methods 
    var getEntityMetadataProperty = function (entityName, metadataProperty) {
        var xml = "";
        xml += "<?xml version='1.0' encoding='utf-8'?>";
        xml += "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">";
        xml += generateAuthenticationHeader();
        xml += "<soap:Body>";
        xml += "<Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>";
        xml += "<Request xsi:type='RetrieveEntityRequest'>";
        xml += "<MetadataId>00000000-0000-0000-0000-000000000000</MetadataId>";
        xml += "<EntityItems />";
        xml += String.format("<LogicalName>{0}</LogicalName>", entityName);
        xml += "<RetrieveAsIfPublished>false</RetrieveAsIfPublished>";
        xml += "</Request>";
        xml += "</Execute>";
        xml += "</soap:Body>";
        xml += "</soap:Envelope>";

        var responseXml = executeCRMMetadataServiceMethod(xml);

        if (Utils.isValue(responseXml)) {
            return getNodeValue(responseXml, metadataProperty);
        }
    };

    var generateAuthenticationHeader = function () {
        if (window.GenerateAuthenticationHeader) {
            return GenerateAuthenticationHeader();
        }
        else if (parent.window.GenerateAuthenticationHeader) {
            return parent.window.GenerateAuthenticationHeader();
        }
    };

    var executeCRMMetadataServiceMethod = function (xml) {
        if (Utils.isValue(Cache[xml])) {
            return Cache[xml];
        }

        var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        xmlHttp.open("POST", "/mscrmservices/2007/metadataservice.asmx", false);
        xmlHttp.setRequestHeader("Content-Type", "text/xml; charset-utf-8");
        xmlHttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
        xmlHttp.send(xml);

        var errorCount = xmlHttp.responseXml.selectNodes('//error').length;
        if (errorCount != 0) {
            var errorMessage = xmlHttp.responseXml.selectSingleNode('//description').nodeTypedValue;
        }
        else if (xmlHttp.status != 200) {
        }
        else {
            Cache[xml] = xmlHttp.responseXml;
            return xmlHttp.responseXml;
        }
    };

    var getNodeValue = function (tree, el) {
        var retVal = null;
        var e = null;
        e = tree.getElementsByTagName(el);

        if (e != null && e[0] != null) {
            retVal = e[0].firstChild.nodeValue;
        }

        // If nothing was found, look for a UserLocLabel inner tag, and try to get the value from there
        if (retVal == null) {
            e = e[0].getElementsByTagName("UserLocLabel");
            if (e != null && e[0] != null) {
                retVal = e[0].firstChild.firstChild.nodeValue;
            }
        }

        return retVal;
    };

    // MetadataService Public Methods 
    return {
        getEntityTypeCode: function (entityName) {
            var typeCode = parseInt(getEntityMetadataProperty(entityName, "ObjectTypeCode"), 10);
            if (!isNaN(typeCode)) {
                return typeCode;
            }
            return null;
        }
    };
} ();

CrmService = function () {
    var generateAuthenticationHeader = function () {
        if (window.GenerateAuthenticationHeader) {
            return GenerateAuthenticationHeader();
        }
        else if (parent.window.GenerateAuthenticationHeader) {
            return parent.window.GenerateAuthenticationHeader();
        }
        else if (opener && opener.GenerateAuthenticationHeader) {
            return opener.GenerateAuthenticationHeader();
        }
    };

    var executeCRMWebServiceMethod = function (methodName, xml) {
        var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        xmlHttp.open("POST", "/mscrmservices/2007/crmservice.asmx", false);
        xmlHttp.setRequestHeader("Content-Type", "text/xml; charset-utf-8");
        xmlHttp.setRequestHeader("SOAPAction", String.format("http://schemas.microsoft.com/crm/2007/WebServices/{0}", methodName));
        xmlHttp.send(xml);

        var errorCount = xmlHttp.responseXml.selectNodes('//error').length;
        if (errorCount != 0) {
            var errorMessage = xmlHttp.responseXml.selectSingleNode('//description').nodeTypedValue;
        }
        else if (xmlHttp.status != 200) {
        }
        else {
            return xmlHttp.responseXml;
        }
    };

    var getNodeValue = function (tree, el) {
        var retVal = null;
        var e = null;
        e = tree.getElementsByTagName(el);

        if (e != null && e[0] != null) {
            retVal = e[0].firstChild.nodeValue;
        }

        return retVal;
    };

    var deserializeBusinessEntityIntoObject = function (businessEntityXmlNode, fields) {
        var result = {};

        // Create a new property for each field passed in.  This way, if it's null and not
        // returned by CRM, we'll still have the property in the result object.
        for (var i = 0; i < fields.length; i++) {
            result[fields[i]] = { value: null, DataValue: null };
        }

        if (businessEntityXmlNode && businessEntityXmlNode.childNodes && businessEntityXmlNode.childNodes.length > 0) {
            for (var i = 0; i < businessEntityXmlNode.childNodes.length; i++) {
                var isDate = false;
                var isNumber = false;
                var isLookup = false;
                var isPicklist = false;

                var childNode = businessEntityXmlNode.childNodes[i];
                var fieldName = childNode.tagName.replace("q1:", "");
                var fieldValue = childNode.text;

                result[fieldName] = {};

                for (var j = 0; j < childNode.attributes.length; j++) {
                    var attributeName = childNode.attributes[j].nodeName;
                    var attributeValue = childNode.attributes[j].nodeValue;

                    result[fieldName][attributeName] = attributeValue;

                    if (attributeName == "date") {
                        isDate = true;
                    }
                    else if (attributeName == "formattedvalue" && !isNaN(fieldValue)) {
                        isNumber = true;
                    }
                    else if (attributeName == "dsc") {
                        isLookup = true;
                    }
                    else if (attributeName == "name") {
                        isPicklist = true;
                    }
                }

                var formattedValue = fieldValue;
                if (isDate) {
                    formattedValue = new Date(result[fieldName].date + " " + result[fieldName].time);
                }
                else if (isNumber) {
                    formattedValue = parseFloat(formattedValue);
                }
                else if (isLookup) {
                    formattedValue = {
                        id: fieldValue,
                        typename: "",
                        name: result[fieldName].name
                    };
                }
                else if (isPicklist) {
                    formattedValue = parseInt(formattedValue);
                }

                result[fieldName].value = fieldValue;
                result[fieldName].DataValue = formattedValue;
            }
        }

        return result;
    };

    function Attribute(attribute, value, type) {
        this.attribute = attribute;
        this.value = value;
        this.type = type;
    };

    Attribute.prototype.toString = function () {
        if (this.type)
            return String.format("<{0} type=\"{1}\">{2}</{0}>", this.attribute, this.type, this.value.toString());
        else
            return String.format("<{0}>{1}</{0}>", this.attribute, this.value.toString());
    };

    // CrmService Public Methods
    return {
        Condition: function (attribute, operator, value) {
            return { attribute: attribute, operator: operator, value: value };
        },

        retrieveMultiple: function (entityName, queryConditions, filterOperator, params_fields) {
            var result = [];

            var authHeader = generateAuthenticationHeader();
            if (Utils.isNull(authHeader)) {
                return result;
            }

            var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
            xml += "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">";
            xml += authHeader;
            xml += "<soap:Body><RetrieveMultiple xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>";
            xml += "<query xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:QueryExpression'>";
            xml += String.format("<q1:EntityName>{0}</q1:EntityName>", entityName);
            xml += "<q1:ColumnSet xsi:type='q1:ColumnSet'><q1:Attributes>";

            var fields = Utils.getArgumentsAsArray(arguments, 3);
            for (var i = 0; i < fields.length; i++) {
                xml += String.format("<q1:Attribute>{0}</q1:Attribute>", fields[i]);
            }

            xml += "</q1:Attributes></q1:ColumnSet>";
            xml += "<q1:Distinct>false</q1:Distinct>";
            xml += String.format("<q1:Criteria><q1:FilterOperator>{0}</q1:FilterOperator><q1:Conditions>", filterOperator);

            var conditionsAsArray = Utils.isArray(queryConditions) ? queryConditions : [queryConditions];

            for (var i = 0; i < conditionsAsArray.length; i++) {
                var currentCondition = conditionsAsArray[i];

                xml += "<q1:Condition>";
                xml += String.format("<q1:AttributeName>{0}</q1:AttributeName>", currentCondition.attribute);
                xml += String.format("<q1:Operator>{0}</q1:Operator>", currentCondition.operator);
                if (Utils.isValue(currentCondition.value)) {
                    var valuesAsArray = Utils.isArray(currentCondition.value) ? currentCondition.value : [currentCondition.value];
                    xml += "<q1:Values>";
                    for (var j = 0; j < valuesAsArray.length; j++) {
                        xml += String.format("<q1:Value xsi:type='xsd:string'>{0}</q1:Value>", valuesAsArray[j]);
                    }
                    xml += "</q1:Values>";
                }
                xml += "</q1:Condition>";
            }

            xml += "</q1:Conditions></q1:Criteria></query></RetrieveMultiple></soap:Body></soap:Envelope>";

            var responseXml = executeCRMWebServiceMethod("RetrieveMultiple", xml);

            if (Utils.isValue(responseXml)) {
                var retrieveResultNodes = responseXml.getElementsByTagName("BusinessEntity");

                if (retrieveResultNodes) {
                    for (var i = 0; i < retrieveResultNodes.length; i++) {
                        result.push(deserializeBusinessEntityIntoObject(retrieveResultNodes[i], fields));
                    }
                }
            }

            return result;
        }
    };
} ();

Utils = function () {
    // Utils Private Methods 
    var hasConstructor = function (o) {
        return o !== null & o !== undefined && o.constructor;
    };

    // Utils Public Methods 
    return {

        isNull: function (o) {
            return (o === null);
        },

        isUndefined: function (o) {
            return (o === undefined);
        },

        isNumber: function (o) {
            return (this.isValue(o) && hasConstructor(o) && o.constructor.toString().indexOf("Number") > 0);
        },

        isValue: function (o) {
            return (!this.isNull(o) && !this.isUndefined(o));
        },

        isArray: function (o) {
            return (this.isValue(o) && hasConstructor(o) && o.constructor.toString().indexOf("Array") > 0);
        },

        isString: function (o) {
            return (this.isValue(o) && hasConstructor(o) && o.constructor.toString().indexOf("String") > 0);
        },

        getArgumentsAsArray: function (args, startIndex) {
            // If startIndex is not a number, default it to 0
            if (!this.isNumber(startIndex)) {
                startIndex = 0;
            }

            var finalResults = [];
            for (var i = startIndex; i < args.length; i++) {
                if (this.isArray(args[i])) {
                    var innerArrayResults = this.getArgumentsAsArray(args[i]);

                    for (var j = 0; j < innerArrayResults.length; j++) {
                        finalResults.push(innerArrayResults[j]);
                    }
                }
                else {
                    if (args[i] !== null) {
                        finalResults.push(args[i]);
                    }
                }
            }

            return finalResults;
        }
    };
} ();

Utils.Guid = function () {
    // Utils.Guid Public Methods 
    return {
        isValid: function (guid) {
            if (!Utils.isString(guid)) {
                return false;
            }

            var hasValidBrackets = (guid.indexOf("{") === -1 && guid.indexOf("}") === -1) ||
									(guid.indexOf("{") === 0 && guid.indexOf("}") === guid.length - 1);

            var guidRegEx = new RegExp(/\{?([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}?$/);

            return hasValidBrackets && guidRegEx.test(guid);
        }
    };
} ();

Cache = function () {
    return {};
} ();

Open in new window

0
 

Author Closing Comment

by:savetheorcas
ID: 35217081
I was able to modify the code to make it work.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

On Sep 22nd 2014 Microsoft released Update Rollup 1 for Microsoft Dynamics CRM 2013 Service Pack 1 and back in July Update Rollup 3 was released.  So we now have:   Update Rollup 1Update Rollup 2Update Rollup 3Service Pack 1Update Rollup 1 for S…
Having trouble getting your hands on Dynamics 365 Field Service or Project Service trial? Worry No More!!!
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…
Suggested Courses

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question