web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Suggested Answer

Expand case primary contact lookup

(0) ShareShare
ReportReport
Posted on by 53

We have a business requirement where we need the ability to expand the Case Primary Contact field. We need the ability to lookup to related Vendors on the account (selected on the case) and display the Vendor contacts with the account contacts in the lookup field.  We often have vendors that call in on behalf of our clients and need to associate the case to them as the primary contact.  Any recommendations on how to go about doing this would be greatly appreciated!  Thanks in advance! 

I have the same question (0)
  • Suggested answer
    ankit_singhal Profile Picture
    560 on at

    You can write Plugin or Power Automate and Populate the lookup value from one entity to another according to your need. I think there is no OOB feature, you need to write custom login only

    Please mark as verified if the answer is helpful.

  • AZWildcat1290 Profile Picture
    53 on at

    Unfortunately I dont think power automate is able to assist on this one as it would have to be real time to pull all contacts that are associated with any vendors that are in connection with our client as well as our client contacts... And there isnt a way to easily populate the lookup from one entity to another as it could potentially be any of the contacts that are ultimately associated with our client...

  • AZWildcat1290 Profile Picture
    53 on at

    We have pulled together this code but its not triggering as expected.  In the developer tools on edge it states "Could not find a property named 'e3_account' on type 'Microsoft.Dynamics.CRM.contact'.  I have verified the field is indeed e3_account.  Please let me know if you see any issues with the code below:

    function getContacts(executionContext) {
        var formContext = executionContext.getFormContext();
        // Get the account lookup value from the case form
        var accountLookup = formContext.getAttribute("e3_client").getValue();
      
        // Check if an account is selected
        if (accountLookup) {
          // Get the account GUID
          var accountId = accountLookup[0].id;
      
          // Define the query to retrieve Vendor Agreement records
          var vendorAgreementQuery = "?$select=_e3_vendor_value&$filter=_e3_client_value eq "   accountId;
      
          // Retrieve Vendor Agreement records and related Vendor records
          Xrm.WebApi.retrieveMultipleRecords("e3_vendoragreement", vendorAgreementQuery).then(
            function(results) {
              // Create an array to hold vendor GUIDs
              var vendorIds = [];
      
              // Loop through the Vendor Agreement records and add each Vendor GUID to the array
              for (var i = 0; i < results.entities.length; i  ) {
                vendorIds.push(results.entities[i]._e3_vendor_value);
              }
      
              // Define the query to retrieve BAA records
              var baaQuery = "?$select=_e3_vendor_value&$filter=_e3_client_value eq "   accountId;
      
              // Retrieve BAA records and related Vendor records
              Xrm.WebApi.retrieveMultipleRecords("e3_businessassociateagreement", baaQuery).then(
                function(results) {
                  // Loop through the BAA records and add each Vendor GUID to the array
                  for (var i = 0; i < results.entities.length; i  ) {
                    vendorIds.push(results.entities[i]._e3_vendor_value);
                  }
      
                  // Remove duplicate Vendor GUIDs from the array
                  var uniqueVendorIds = vendorIds.filter(function(item, index, self) {
                    return index === self.indexOf(item);
                  });
      
                  // Define the query to retrieve Contact records
                  var contactQuery = "?$select=fullname&$filter=";
                  contactQuery  = "(e3_account/e3_account_contact_account/any(o:o/e3_account eq ";
                  contactQuery  = accountId   ")) or (e3_vendoraccount/e3_e3_vendor_contact_vendoraccount/any(o:o/e3_vendoraccount eq ";
                  contactQuery  = uniqueVendorIds.join(" or e3_vendor eq ")   "))";
      
                  // Retrieve Contact records
                  Xrm.WebApi.retrieveMultipleRecords("contact", contactQuery).then(
                    function(results) {
                      // Create an array to hold Contact GUIDs
                      var contactIds = [];
      
                      // Loop through the Contact records and add each Contact GUID to the array
                      for (var i = 0; i < results.entities.length; i  ) {
                        contactIds.push(results.entities[i].contactid);
                      }
      
                      // Set the primary contact lookup field value to the array of Contact GUIDs
                      Xrm.Page.getAttribute("primarycontactid").setValue(contactIds);
                    },
                    function(error) {
                      console.log(error.message);
                    }
                  );
                },
                function(error) {
                  console.log(error.message);
                }
              );
            },
            function(error) {
              console.log(error.message);
            }
          );
        }
      }
    

  • Suggested answer
    XM-22040801-0 Profile Picture
    11 on at

    Hi,

    I think this behavior should be done in Power Automate or a plugin.

    However, I have modified your javascript code, and I have some questions.

    async function getContacts(executionContext) {
        const formContext = executionContext.getFormContext();
        const accountLookup = formContext.getAttribute("e3_client").getValue();
    
        if (!accountLookup) {
            return; // No account lookup value, so exit the function
        }
    
        try {
            // Get the account GUID
            const accountId = accountLookup[0].id;
    
            // Retrieve Vendor Agreement and BAA
            const vaPromise = Xrm.WebApi.retrieveMultipleRecords("e3_vendoragreement", `?$select=_e3_vendor_value&$filter=_e3_client_value eq ${accountId}`);
            const baaPromise = Xrm.WebApi.retrieveMultipleRecords("e3_businessassociateagreement", `?$select=_e3_vendor_value&$filter=_e3_client_value eq ${accountId}`);
    
            const [vaRecords, baaRecords] = await Promise.all([vaPromise, baaPromise]); // Wait for both promises to resolve. Improves performance.
    
            const uniqueVendorIds = [...new Set( // Remove duplicates. See https://stackoverflow.com/a/14438954/2001966
                [...vaRecords.entities, ...baaRecords.entities] // Combine the two arrays with the spread operator
                    .map(entity => entity._e3_vendor_value) // Get the vendor lookup value
            )];
    
            if (uniqueVendorIds.length === 0) {
                throw new Error("No vendor agreements or business associate agreements found.");
            }
    
            // IMPORTANT: I am not sure about this query, can you tell more about the relationship between the entities?
            const contactQuery = `?$select=fullname&$filter=(e3_account/e3_account_contact_account/any(o:o/e3_account eq ${accountId}))`  
                `or (e3_vendoraccount/e3_e3_vendor_contact_vendoraccount/any(o:o/e3_vendoraccount eq ${uniqueVendorIds.join(" or e3_vendor eq ")}))`;
    
            // Retrieve Contact records
            const contactsResult = await Xrm.WebApi.retrieveMultipleRecords("contact", contactQuery);
    
            if (contactsResult.entities.length === 0) {
                throw new Error("No contacts found.");
            }
    
            if (contactsResult.entities.length > 1) {
                formContext.ui.setFormNotification(`Found ${contactLookupValues.length} contacts. Only the first one will be set as primary.`, "WARNING", "1");
            }
    
            // Create an array of lookup values
            const contactLookupValues = contactsResult.entities
                .map(entity => ({
                    id: entity.contactid,
                    name: entity.fullname,
                    entityType: "contact"
                }));
    
            formContext.getAttribute("primarycontactid").setValue([contactLookupValues[0]]); // Only one contact can be set as primary
        }
        catch (error) {
            Xrm.Navigation.openAlertDialog({ text: `An error was occurred: ${error.message}. Stacktrace: ${error.stack}` });
        }
    }

    I used modern javascript code: const, promises with async/await, set, map, string interpolation, spread operator, arrow function...
    I fixed a problem with the lookup assignment. The primarycontactid lookup can only take one contact and it must be assigned as an object with id, name, entityType properties. What should you do if there are multiple contacts?

    However, I think your problem is located in the contactQuery. Can you tell me more about the relationship between the entities?

  • AZWildcat1290 Profile Picture
    53 on at

    Hi Xavier Monin! Thank you so much for your response! The case will only ever have one contact set as a primary contact.  As for the relationships we have:

    - Vendor Agreements and BAAs: have a N:1 relationship with Accounts and Vendors

    - Vendors and Accounts: have a 1:N relationship with Contacts (I should note that contacts will either have a vendor or an account in our system as they are separate fields on the contact record)

    So when we pull the contacts into the lookup for Primary Contact on a case we want to pull all contact records that are involved with an account whether they be directly with the account or with the vendor.  

  • AZWildcat1290 Profile Picture
    53 on at

    Unfortunately still getting this error "An error was occurred: Could not find a property named 'accountid' on type 'Microsoft.Dynamics.CRM.contact'.. Stacktrace: undefined"

  • XM-22040801-0 Profile Picture
    11 on at

    Can you create a FetchXML (with FetchXML Builder from XrmToolBox) that fetches contacts (there should be only one record) from an accounttid and a list of uniqueVendorIds?

    It will be easier for me to help you with an existing Fetch XML (Fetch XML can be used in javascript).

    Objective: Do what the contactQuery should do.

  • XM-22040801-0 Profile Picture
    11 on at

    Can you tell me the line affected ? (with the browser debugger)

  • AZWildcat1290 Profile Picture
    53 on at

    Not sure this is correct... I've never used fetchXML before but this is what i entered/what was given back:

    Request:

    <fetch mapping='logical'>

       <entity name='contact'>

           <attribute name ='e3_account'/>

           <attribute name ='parentcustomerid'/>

           <attribute name = 'accountid'/>

           <attribute name ='e3_vendoraccount'/>

       </entity>

    </fetch>

    Response:

    <resultset morerecords="0" paging-cookie="<cookie page="1"><contactid last="{481B839B-1250-47F1-872A-972987EEE7E5}" first="{0AF70D5D-01E9-EC11-BB3C-000D3A5640CD}" /></cookie>">

     <result>

       <e3_account name="Contoso" yomi="" type="1">{0BF70D5D-01E9-EC11-BB3C-000D3A5640CD}</e3_account>

       <parentcustomerid type="1" dsc="" name="Contoso" yomi="">{0BF70D5D-01E9-EC11-BB3C-000D3A5640CD}</parentcustomerid>

       <contactid>{0AF70D5D-01E9-EC11-BB3C-000D3A5640CD}</contactid>

     </result>  

     <result>

       <e3_vendoraccount name="Vendor" type="10466">{5AD6CC5C-95E2-EC11-BB3D-0022481E9D95}</e3_vendoraccount>

       <contactid>{4860E8A6-E86C-ED11-9562-00224824973C}</contactid>

     </result>

    </resultset>

    (Shortened the results so that it wasnt a huge post...)

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

News and Announcements

Season of Giving Solutions is Here!

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Pallavi Phade Profile Picture

Pallavi Phade 98

#2
Tom_Gioielli Profile Picture

Tom_Gioielli 79 Super User 2025 Season 2

#3
TAHER Mehdi Profile Picture

TAHER Mehdi 48

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans