Thursday, January 15, 2015

Update parent record based on multiple fields

Here’s an extremely simplified example of a plug-in. We have parent record with a field for total, and a single child with unit and rate. When either unit or rate changes, we want to multiply these and update to the total of the parent.
Design Notes
  • Because user may only update units and not update rate, we cannot use target which would only include the attributes that were actually updated. Therefore, we use image to make sure we get the necessary attributes, without having to do additional data retrieve.
  • The plug-in is post-update, so we will have access to post-image, showing all values like they are after update.
  • When registering the plugin, we set filtering attributes to include only rate and units. Therefore, plugin will not trigger needlessly if something unrelated updates.
  • When setting up the Image, we only need rate, units and parent ID.
Plug-in Code
using System;
using Microsoft.Xrm.Sdk;

namespace CRM
{
    public class Update : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context =
                (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            // Get a reference to the Organization service.
            IOrganizationServiceFactory factory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);

            if (context.InputParameters != null)
            {
                //entity = (Entity)context.InputParameters["Target"];
                //Instead of getting entity from Target, we use the Image
                Entity entity = context.PostEntityImages["PostImage"];

                Money rate = (Money)entity.Attributes["po_rate"];
                int units = (int)entity.Attributes["po_units"];
                EntityReference parent = (EntityReference)entity.Attributes["po_parentid"];

                //Multiply
                Money total = new Money(rate.Value * units);

                //Set the update entity
                Entity parententity = new Entity("po_parententity");
                parententity.Id = parent.Id;
                parententity.Attributes["po_total"] = total;

                //Update
                service.Update(parententity);

            }

        }

    }
}

No comments:

Post a Comment