Muhammad Usman Khan
Muhammad Usman Khan

Reputation: 25

Auto populate lookup field through plugin in C# plugin in Dynamic CRM

I am trying to auto populate account lookup field in my form upon selection of contact lookup field but when i perform it shows entity does not contain the respective id but when i debug it shows the right account name can any one let me know where i am making mistake?

Entity task = (Entity)context.InputParameters["Target"];
EntityReference lookupValue = task.GetAttributeValue<EntityReference>("new_contact");

if (lookupValue != null)
{
    string targetEntityName = lookupValue.LogicalName;
    Guid targetEntityId = lookupValue.Id;
    QueryExpression query_contactparty = new QueryExpression("contact");
    query_contactparty.Criteria = new FilterExpression();
    query_contactparty.ColumnSet.AddColumns("contactid");
    query_contactparty.ColumnSet.AddColumns("fullname");
    query_contactparty.ColumnSet.AddColumns("parentcustomerid");
    query_contactparty.Criteria.AddCondition("contactid", ConditionOperator.Equal, targetEntityId);

    LinkEntity accountLink = new LinkEntity("contact", "account", "parentcustomerid", "accountid", JoinOperator.Inner);
    accountLink.Columns = new ColumnSet("name");
    query_contactparty.LinkEntities.Add(accountLink);

    EntityCollection contactparty = service.RetrieveMultiple(query_contactparty);

    foreach (var con in contactparty.Entities)
    {
        Guid accountid = con.GetAttributeValue<Guid>("contactid");
        string name = con.GetAttributeValue<string>("fullname");
        EntityReference parentAccount = con.GetAttributeValue<EntityReference>("parentcustomerid");

        if (parentAccount != null)
        {
            //throw new InvalidPluginExecutionException("Value found is:" + name + " and id is: " + accountid + " account :" + parentAccount.Name);

            task["new_account"] = new EntityReference("new_kaispe", parentAccount.Id)
            {
                Name = parentAccount.Name
            };
        }

        service.Update(task);
    }
}

Upvotes: 0

Views: 541

Answers (1)

Henk van Boeijen
Henk van Boeijen

Reputation: 7918

In a plugin pipeline handling the Update message, an EntityReference value can be set in the pre validation stage. The Entity found in the "Target" property of the InputParameters collection only needs to be modified. Do not try to update it using service.Update(task).

Just remove that line and register your plugin for the pre validation stage.

Upvotes: 1

Related Questions