Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Answered

Get Related Subgrid record from Lookup & set records in Parent subgrid in CRM 365 on Create using Plugin

Posted on by 2,665

Hi All,

In case entity Asset & Division lookup field is present & one subgrid to User is exists.

In Asset & Division both entity Subgrid with User is there.So here in Case based on asset or division lookup selection need to get  subgrid records & set in Case entity Subgrid using Plugin.

Any link or code Can anyone share here,it would be helpful.

Thanks,

Jharana

  • Jharana Baliyar Singh Profile Picture
    Jharana Baliyar Singh 2,665 on at
    RE: Get Related Subgrid record from Lookup & set records in Parent subgrid in CRM 365 on Create using Plugin

    Thank you Bipin ya got this & found the cause.

    Thanks again !!

  • Verified answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: Get Related Subgrid record from Lookup & set records in Parent subgrid in CRM 365 on Create using Plugin

    Hi,

    Please check plugin trace log and you will figure out till what point it is working.

    I have checked your code. It seems below line is the problem as you are getting Id without checking null on entityreference object.

    EntityReference division = entityCase.Attributes.Contains("mdc_relateddivision") ? entityCase?.GetAttributeValue<EntityReference>("mdc_relateddivision") : null;

                          EntityReference asset = entityCase.Attributes.Contains("mdc_relatedasset") ? entityCase?.GetAttributeValue<EntityReference>("mdc_relatedasset") : null;

                          tracingService.Trace("Division got...." + division.Id);

                          tracingService.Trace("Asset got...." + asset.Id);

    Please mark my answer verified if i were helpful

  • Jharana Baliyar Singh Profile Picture
    Jharana Baliyar Singh 2,665 on at
    RE: Get Related Subgrid record from Lookup & set records in Parent subgrid in CRM 365 on Create using Plugin

    Thanks Bipin I used the associate on create its working fine but on update of division i am not able to do i checked in console its working but in plugin am getting error Object not set to reference an object .

    Please find the below where i am going wrong, am checking null all where but not able to find out the issue as cant debug the code as its onpremise & in server no vs exists.

    try

               {

                   IPluginExecutionContext executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                   ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

                   IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                   organizationService = serviceFactory.CreateOrganizationService(executionContext.UserId);

                   organizationServiceContext = new OrganizationServiceContext(organizationService);

                   Entity incident = new Entity();

                   bool IsGridData = false;

                   if (executionContext.MessageName.ToUpper() == "UPDATE")

                   {

                       if (executionContext.InputParameters.Contains("Target") && (executionContext.InputParameters["Target"] is Entity))

                       {

                           if ((Entity)executionContext?.InputParameters["Target"] != null)

                               incident = (Entity)executionContext.InputParameters["Target"];

                           tracingService.Trace("Got Incident");

                           //EntityReference categoryType = null;

                           //Entity createPostImage = (Entity)executionContext.PostEntityImages["ConflictofInterestPostImage"];

                           //if (createPostImage.Contains("mdc_interactiontype"))

                           //    categoryType = (EntityReference)createPostImage["mdc_interactiontype"];

                           ColumnSet attributes = new ColumnSet(new string[] { "mdc_relateddivision", "mdc_relatedasset" });

                           Entity entityCase = organizationService.Retrieve(incident.LogicalName, incident.Id, attributes);

                           EntityReference division = entityCase.Attributes.Contains("mdc_relateddivision") ? entityCase?.GetAttributeValue<EntityReference>("mdc_relateddivision") : null;

                           EntityReference asset = entityCase.Attributes.Contains("mdc_relatedasset") ? entityCase?.GetAttributeValue<EntityReference>("mdc_relatedasset") : null;

                           tracingService.Trace("Division got...." + division.Id);

                           tracingService.Trace("Asset got...." + asset.Id);

                           if (entityCase.Attributes.Contains("mdc_relateddivision") && division?.Id != null )

                           {

                               divisionId = (entityCase.GetAttributeValue<EntityReference>("mdc_relateddivision")).Id;

                               tracingService.Trace($"Got Division Id here....: " + divisionId);

                               //Retrieving Compliance Counsel grid records

                               ConditionExpression condition = new ConditionExpression();

                               condition.AttributeName = "mdc_compliancecounselid";

                               condition.Operator = ConditionOperator.Equal;

                               if (incident?.Id != null && incident?.Id != Guid.Empty)

                                   condition.Values.Add(incident.Id);

                               //Create a column set.

                               ColumnSet columns = new ColumnSet(true);

                               QueryExpression query1 = new QueryExpression();

                               query1.ColumnSet = columns;

                               query1.EntityName = "systemuser";

                               query1.Criteria.AddCondition(condition);

                               List<Entity> relatedUsers = new List<Entity>();

                               EntityCollection resColl = organizationService.RetrieveMultiple(query1);

                               tracingService.Trace($"Subgrid records" + resColl.Entities.Count);

                               if (resColl?.Entities != null)

                               {

                                   IsGridData = true;

                                   tracingService.Trace($"subgrid has data");

                                   foreach (var r in resColl.Entities)

                                   {

                                       relatedUsers.Add(r);

                                       DisassociateRequest disassociateReq = new DisassociateRequest();

                                       if (incident?.Id != null && incident.Id != Guid.Empty)

                                           disassociateReq.Target = new EntityReference("incident", incident.Id);

                                       disassociateReq.RelatedEntities = new EntityReferenceCollection();

                                       if (r?.Id != null)

                                           disassociateReq.RelatedEntities.Add(new EntityReference("systemuser", r.Id));

                                       disassociateReq.Relationship = new Relationship("mdc_incident_systemuser");

                                       if (disassociateReq != null)

                                           organizationService.Execute(disassociateReq);

                                       tracingService.Trace($"Disaasociated Users successfully");

                                   }

                               }

                               if (IsGridData)  //Check Compliance Counsel grid has no records then Associate Users

                               {

                                   tracingService.Trace($"Grid has no records");

                                   QueryExpression query = new QueryExpression();

                                   query.EntityName = "systemuser";

                                   query.ColumnSet = new ColumnSet(true);

                                   Relationship relationship = new Relationship();

                                   query.Criteria = new FilterExpression();

                                   relationship.SchemaName = "mdc_mdc_division_systemuser";

                                   tracingService.Trace($"Relationship exists");

                                   RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();

                                   if (relationship != null && query != null)

                                       relatedEntity.Add(relationship, query);

                                   RetrieveRequest request = new RetrieveRequest();

                                   request.RelatedEntitiesQuery = relatedEntity;

                                   request.ColumnSet = new ColumnSet("mdc_divisionid");

                                   if (divisionId != null)

                                       request.Target = new EntityReference { Id = divisionId, LogicalName = "mdc_division" };

                                   RetrieveResponse response = (RetrieveResponse)organizationService.Execute(request);

                                   tracingService.Trace($"Got Response");

                                  List<Entity> relatedEntities = new List<Entity>();

                                   if (((((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Relationship("mdc_mdc_division_systemuser")) &&

                                   ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_division_systemuser")].Entities.Count > 0)

                                   {

                                       foreach (var item in ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_division_systemuser")].Entities)

                                       {

                                           relatedEntities.Add(item);

                                           AssociateRequest request1 = new AssociateRequest();

                                           if (incident?.Id != null)

                                               request1.Target = new EntityReference(incident.LogicalName, incident.Id);

                                           request1.RelatedEntities = new EntityReferenceCollection();

                                           if (item?.Id != null)

                                               request1.RelatedEntities.Add(new EntityReference("systemuser", item.Id));

                                           request1.Relationship = new Relationship("mdc_incident_systemuser");

                                           organizationService.Execute(request1);

                                           tracingService.Trace($"Associated Users successfully");

                                       }

                                   }

                               }

                           }

                           //else if(entityCase.Attributes.Contains("mdc_relatedasset") && asset != null)

                           //{

                           //  assetId = (entityCase.GetAttributeValue<EntityReference>("mdc_relatedasset")).Id;

                           //  tracingService.Trace($"Got Asset Id here....: " + assetId);

                           //}

                       }

                   }

               }

               catch (Exception ex)

               {

                   throw new InvalidPluginExecutionException("An error occurred in the Update GE Compliance counsel Plug-in: " + ex.Message, ex);

               }

    Please let me know it will be helpful.

    Thanks

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: Get Related Subgrid record from Lookup & set records in Parent subgrid in CRM 365 on Create using Plugin

    Hi,

    To add records to Case sugbrid, you will need to use associate request. See below sample code.

    docs.microsoft.com/.../microsoft.xrm.sdk.messages.associaterequest

    Please mark my answer verified if i were helpful

  • Jharana Baliyar Singh Profile Picture
    Jharana Baliyar Singh 2,665 on at
    RE: Get Related Subgrid record from Lookup & set records in Parent subgrid in CRM 365 on Create using Plugin

    Hi All,

    I have tried with below code to get related subgrid details division to User(N:N relationship) & getting all the users associated with Division now need to set those users in Case subgrid (User).

    So for setting the users deatils in Case. Any link or or code can anyone share here, it  will be helpful .

    The below code :

    string entityId = "1da6fa7d-4edd-ea11-a824-001dd8b70014"; //Case record id

                            ColumnSet attributes = new ColumnSet(new string[] { "mdc_reportername", "mdc_reporterisnotanmicuser", "mdc_relateddivision", "mdc_relatedasset" });

                   Entity enCase = _crmService.Retrieve("incident", Guid.Parse(entityId), attributes);

                   EntityReference division = enCase.Attributes.Contains("mdc_relateddivision") ? enCase.GetAttributeValue<EntityReference>("mdc_relateddivision") : null;

                   if (enCase.Attributes.Contains("mdc_relateddivision") && division != null)

                   {

                   divisionId = (enCase.GetAttributeValue<EntityReference>("mdc_relateddivision")).Id;

                       Console.WriteLine("Division From Case : " + divisionId);

                       Console.ReadLine();

                       //create the query expression object

                       List<UserDetails> user = new List<UserDetails>();

                       QueryExpression query = new QueryExpression();

                       query.EntityName = "systemuser";

                       query.ColumnSet = new ColumnSet(true);

                       //create the relationship object

                       Relationship relationship = new Relationship();                

                       query.Criteria = new FilterExpression();

                       //query.Criteria.AddCondition(new ConditionExpression("statecode", ConditionOperator.Equal, "Active"));

                       // name of relationship between division & user

                       relationship.SchemaName = "mdc_mdc_division_systemuser";

                       //create relationshipQueryCollection Object

                       RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();

                       //Add the your relation and query to the RelationshipQueryCollection

                       relatedEntity.Add(relationship, query);

                       //create the retrieve request object

                       RetrieveRequest request = new RetrieveRequest();

                       //add the relatedentities query

                       request.RelatedEntitiesQuery = relatedEntity;

                       //set column to and the condition for the account

                       request.ColumnSet = new ColumnSet("mdc_divisionid");

                       request.Target = new EntityReference { Id = divisionId, LogicalName = "mdc_division" };

                       //execute the request

                       RetrieveResponse response = (RetrieveResponse)_crmService.Execute(request);                  

                       List<Entity> relatedEntities = new List<Entity>();

                       // here you can check collection count

                       if (((((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Relationship("mdc_mdc_division_systemuser")) &&

                       ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_division_systemuser")].Entities.Count > 0)

                       {

                           foreach (var item in ((((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("mdc_mdc_division_systemuser")].Entities)

                           {

                               relatedEntities.Add(item);

                           }

                           Console.WriteLine("Got Users details");

                           Console.ReadLine();

                       }                  

                   }

    Thanks,

    Jharana

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: Get Related Subgrid record from Lookup & set records in Parent subgrid in CRM 365 on Create using Plugin

    Hi,

    Please see below article which has set of sample code fo plugins to starts with.

    docs.microsoft.com/.../basic-followup-plugin

    Please mark my answer verified if i were helpful

  • Jharana Baliyar Singh Profile Picture
    Jharana Baliyar Singh 2,665 on at
    RE: Get Related Subgrid record from Lookup & set records in Parent subgrid in CRM 365 on Create using Plugin

    Hi Leah,

    Thanks for the response.I need to do using Plugin not from Js side.

    Any links for C# let me know.

    Thanks,

    Jharana

  • Suggested answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Get Related Subgrid record from Lookup & set records in Parent subgrid in CRM 365 on Create using Plugin

    Hi Jharana,

    1.Get Id of lookup field.

    https://santoshmscrm.wordpress.com/2015/06/22/how-to-retrieve-lookup-name-and-id-through-plugin/

    2.use CRM REST Builder(https://github.com/jlattimer/CRMRESTBuilder) to retrieve related records based on id.

    you can refer following link:

    https://community.dynamics.com/crm/f/microsoft-dynamics-crm-forum/164176/get-lookup-record-details-and-child-records-in-one-request-using-soap-or-odata/399227

    3.use CRM REST Builder to create records to subgrid.

    https://community.dynamics.com/crm/f/microsoft-dynamics-crm-forum/272889/adding-new-record-to-subgrid-using-javascript/775712

    Regards,

    Leah Ju

    Please mark as verified if the answer is helpful. Welcome to join hot discussions in Dynamics 365 Forums.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans