Search code examples
c#dynamics-crmmicrosoft-dynamics

CRM Plugin: how to update email address of account soon after its creation


I'm using Microsoft Dynamics CRM 2016 on-premise version.

I have an "account" entity and I want to update that account email with hardcoded value soon after its creation.

I want to do this in a plug-in which runs on the "account" entity when you create that account. When you do so, email address of that account gets created.

I've done a bit of searching for this, but there's nothing out there which shows the email ADDRESS getting updated.


Solution

  • So if you really want to do your things after creation of account: You need to register your plugin on Post Operation and after that target entity has to be updated via Organization Service. Like: Post Operation:

    target["emailaddress1"] = "new@test.com";
    organizationService.Update(target);
    

    OR Just use Pre Operation change the email address and that's it.

    Here is a sample:

    public class TestPurpose : IPlugin
        {
            private Entity target;
    
            public void Execute(IServiceProvider serviceProvider)
            {
                IPluginExecutionContext pluginExecutionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                IOrganizationServiceFactory organizationServiceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                IOrganizationService organizationService = organizationServiceFactory.CreateOrganizationService(pluginExecutionContext.UserId);
                target = pluginExecutionContext.InputParameters["Target"] as Entity;
                //This is what you need
                target["emailaddress1"] = "test@test.test";
                organizationService.Update(target);
            }
        }