Dynamics CRM: Don’t use setRequiredLevel(“always”) manually!

On our customization, it is very common if we are disabled some of the attributes. But when a specific attribute changes, we want to set automatically the value of the disabled attribute and save that value in our database. The problem is CRM will skip all the disabled attributes and we end up using the setRequiredLevel(“always”).

This design leads to a problem if the user still using the screen to change another attribute after the method setRequiredLevel(“always”) being called. When the user saves the data, the InputParameters[“Target”] will always get this attribute (also if we set this attribute as a Filtering Attributes property, then our plugin will keep trigger).

How to Solve it?

a) The easiest way is every time you save your data. Refresh the UI (User Interface) using JavaScript. Usually, I will put attribute Modified On Change and register the new event on a change to call this code:

function ModifiedOnChange() {
    if (Xrm.Page.ui.getFormType() === 1) return;

    var entityId = Xrm.Page.data.entity.getId();
	var entityName = Xrm.Page.data.entity.getEntityName();
    Xrm.Utility.openEntityForm(entityName, entityId);
}

b) This one I think more elegant. But of course, we need to scan all the attributes to get if it changes or not. But before using this method, you need to remove all the setSubmitMode(“always”) from existing Javascript and call this function when Form OnLoad:

function scanDataBeforeSave() {
	var loaded;
	var scanDisabledFn = function () {
		Xrm.Page.ui.controls.forEach(function (ctrl) {
			var ctrlName = ctrl.getName();
			var attribute = Xrm.Page.getAttribute(ctrlName);
			if (!attribute) return;
			if (!ctrl.getDisabled || !attribute.getIsDirty) return;

			var isDisabled = ctrl.getDisabled();
			var isDirty = attribute.getIsDirty();
			var submitMode = isDisabled && isDirty ? "always" : "dirty";
			attribute.setSubmitMode(submitMode);
		});
	}
	return function() {
		if (!loaded) {
			Xrm.Page.data.entity.addOnSave(scanDisabledFn);
			loaded = true;
		}
	}();
};

When finished, you can try the customization and finished!

result

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.