Restrict contact deletion on account delete

As per the OOB functionality all the child records of account like contacts, opportunities and activities etc., will be deleted on delete of account. But, in one of my project we got a requirement to remove the link with contacts instead of delete. I tried to customize the relationship but the CRM is not allowing us to do this.

2018-11-05_1514

Finally we ended up with writing the plugin to achieve this. We have to write this plugin on “Pre Validation” stage of “Delete” step on Account entity. The child records were not available in any other steps (Pre Operation for ex) as the CRM platform deletes all the child records first and then account. The following is the plugin code.


IPluginExecutionContext pluginContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService organizationService = serviceFactory.CreateOrganizationService(pluginContext.UserId);
EntityReference targetEntity = (EntityReference)pluginContext.InputParameters["Target"];

QueryExpression getContacts = new QueryExpression("contact");
getContacts.Criteria.AddCondition(new ConditionExpression("parentcustomerid", ConditionOperator.Equal, targetEntity.Id));
EntityCollection allContacts = organizationService.RetrieveMultiple(getContacts);
foreach(Entity contact in allContacts.Entities)
{
Entity contactToBeUpdated = new Entity("contact");
contactToBeUpdated.Id = contact.Id;
contactToBeUpdated.Attributes["parentcustomerid"] = null;
organizationService.Update(contactToBeUpdated);
}

Happy coding !!!

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 )

Google photo

You are commenting using your Google 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