Set lookup from another lookup in current form not working

0
54
Forum Post: Change the Filter On option on Opportunity Associated View for Account form


my current goal is to write a Dynamics plugin, which triggers on update in the opportunity form and gets the account(lookup-contact) of the current contact(lookup-opportunity) and sets it to the account(lookup-opportunity) in the opportunity form.
My problem right now is, that dynamics is not accepting my data, but I can’t find the error.
The debugger says, that the entity contains valid data and I’ve also checked the GUID’s for correct references (and the GUID’s in the excel table exports).

The plugin triggers at PreValidation.

Maybe someone sees the error or can lead me to the correct way?

Edit: The main goal is to apply the company of the contact in the opportunity form automatically, if a company is linked to the contact. 

Thank you!

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;

namespace GetAccountFromContact
{
    public class GetAccountFromContact : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            try

            {
                IPluginExecutionContext context = (IPluginExecutionContext)
                    serviceProvider.GetService(typeof(IPluginExecutionContext));
                IOrganizationServiceFactory serviceFactory =
                        (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                if (context.Depth > 1)

                    return;

                Entity entity = (Entity)context.InputParameters["Target"];
                if (entity.Contains("parentcontactid"))
                {
                    EntityReference pcontact = (EntityReference)entity.Attributes["parentcontactid"];
                    var pcontactid = pcontact.Id; 
                    ColumnSet cols = new ColumnSet(new string[] { "parentcustomerid" }); 

                    Entity paccount = (Entity)service.Retrieve("contact", pcontactid, cols);
                    EntityReference paccountref = (EntityReference)paccount.Attributes["parentcustomerid"];
                    
                    var lookupid = paccountref.Id;
                    var logicalname = paccountref.LogicalName;
                    entity["parentaccountid"] = new EntityReference(logicalname, lookupid);
                    service.Update(entity);
                }
            }
            catch (Exception ex)

            {
                throw new InvalidPluginExecutionException("Plugin Error: " + ex);
            }
        }
    }
}



Source link

Leave a reply

Please enter your comment!
Please enter your name here