Dynamics CRM 365: Set Parent-Child Mapping From Correct Relationship

Let’s say you have Entity Master and Entity Child. Then you want to have a scenario like from the master you want to have two subgrids. If you click the button add on subgrid 1, you want to fill in Child.Master1 and then click the button add on subgrid 2, you want to fill in Child.Master2 only.

By default, CRM will make default mapping. You can pass on the data from parent to a child easily using this way (as long as you doing it in the UI).

default mapping

For this scenario, the easiest way is just to remove mapping that we don’t want to. But the problem is when you want to delete one of the mappings, CRM blocks us to do it. The error given is Cannot create or delete a system AttributeMap.

Then the only way to achieve our scenario is by customization only and here are my steps to solve it:

Create a new webresource using this code:

var lib = {}; 
var constant = { SUBGRID_ATTRIBUTE_KEY: 'subgrid-attribute-key' }; 
(function(){
	this.subgridOnLoad = function(control) {
		var valid = control && control._relationship && control._relationship.attributeName;
		if(!valid) return;
		
		var attributeName = control._relationship.attributeName;
		sessionStorage.setItem(constant.SUBGRID_ATTRIBUTE_KEY, attributeName);     
	};     
	
	this.removeValueBasedOnSubgrid = function(sourceAttributes, formContext){         
		var attribute = sessionStorage.getItem(constant.SUBGRID_ATTRIBUTE_KEY);
		if(!attribute) return;
		for(var i in sourceAttributes){
			var currentAttr = sourceAttributes[i];
			if(currentAttr === attribute) continue;
			
			var attr = formContext.getAttribute(currentAttr); 
			if(!attr) continue;
			attr.setValue(null);         
		}     
	}; 
}).apply(lib);

Custom your Add New button on subgrid and calling your javascript function like this:ribbon-editor-custom

Create new javascript for loading the code in Child Entity:

var Test = {}; 
(function(){     
	this.formOnLoad = function(executionObject){         
		var formContext = executionObject.getFormContext();
		lib.removeValueBasedOnSubgrid(['new_master1', 'new_master2'], formContext);    
	}; 
}).apply(Test);

Add the first javascript and the new as lib in Entity Child and register the new event on Form On Load (don’t forget to pass execution context):register-event

When finished, publish all customization and you can try the result!

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.