Javascript – Set any value

Previously I have shown standard functions I use to get text values of attributes and set option sets based on their text value. Here is another common function I use to set the value of any field.(Except lookups which need more parameters, I will cover these later!)

// *** FUNCTION : SetValue
// *** PARAMS :
// ***     fieldName = the name of the attribute to change
// ***     value = the new value for the field
function SetValue(fieldName, value) {
	try {
		// ** If checks that field exists
		if (Xrm.Page.getAttribute(fieldName) != null) {
			// *** Blanks strings are "", blank dates and numbers will be null
			var nullValue = null;
			if (Xrm.Page.getAttribute(fieldName).getAttributeType() == "string") {
				nullValue = "";
			}
			if (value == null || value == "") {
				value = nullValue;
			}
			// *** Set the valkue and also forcse submit (to ensure readonly fields get updated.
			Xrm.Page.getAttribute(fieldName).setValue(value);
			Xrm.Page.getAttribute(fieldName).setSubmitMode("always");
		} else {
			// *** Field doesn't exist, so give a warning message
			alert("Failed to set field: " + fieldName + " is unknown!");
		}
	}
	catch (e) {
		// *** Something went wrong, give an error message
		alert("Error in SetValue:" + "(fieldName = " + fieldName + " value = " + value + ") Error = " + e);
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s