Home > Mobile >  Getting the target entity attribute value (c# pluigin)
Getting the target entity attribute value (c# pluigin)

Time:02-02

My plugin is ran when a value is changed on a form. I am trying to pass in the 'name' attribute of the target entity as a variable. However, the name is showing as blank in my trace log. The attribute logical name is correct and there is a value in the form. Also, the Id is passing through OK so the target entity is working.

I tried defining 'entityName' as both var and string but neither work.

Can anyone advise what I am doing wrong below?

public void Execute(IServiceProvider serviceProvider)
{
    ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

    Entity entityTarget = context.InputParameters["Target"] as Entity;
    Guid guid = entityTarget.Id;
    var entityName = entityTarget.GetAttributeValue<string>("new_name");
    tracingService.Trace("entityName = "   entityName);
}

CodePudding user response:

When attribute new_name is not modified, it will not be part of the Attributes collection in the "Target" entity.

Attributes that have not been modified must be retrieved from a pre entity image.

Entity entityTarget = context.InputParameters["Target"] as Entity;
Entity originalEntity = context.PreEntityImages.Values.FirstOrDefault();

if (!entityTarget.TryGetAttributeValue<string>("new_name", out string entityName))
    entityName = originalEntity.GetAttributeValue<string>("new_name");

tracingService.Trace("entityName = "   entityName);

Remember you need to register this pre image on the update plugin step and in the image attribute new_name must be selected.

  • Related