Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

Autopopulate Lookup when only one value exists

Posted on by Microsoft Employee

I am very, very, very new to CRM, but not new to development.   I hope this post will allow me to ask a question that I have researched for weeks but have not been able to find anything resembling on what I am trying to accomplish.  I am sure it is simple because all the examples I see are for situations far more complex than I am asking.  

I have an Entity A, which has an N:N relationship to Contact.  I have another Entity B which relates to the Entity A/Contact combination.   I have a Subgrid on Contact and when I Add New Entity B, the form opens.   The Contact automatically populates.   The Entity A lookup is set to only show Entity A records that relate to the Contact.    In most instances, there is only one value in the Entity A lookup.  I would like to know how to autopopulate the Entity A lookup with the only value when only one values is possible.

Please do not tell me "it can be done with workflow, javascript, or a plugin" as I wouldn't know where to begin. I would think this is a simple request, however, it seems to be something only I have asked.

*This post is locked for comments

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Autopopulate Lookup when only one value exists

    Thank you.  It is much more readable without all the escapes for quotes too.   I did have to modify the variable name contactID, but finally got it working.  I have 3 more pages to update with the same logic, its the only code I have to write for the app so far. My first CRM app!! Thanks again!

  • Verified answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: Autopopulate Lookup when only one value exists

    Hi Marsox,

    Seems in your fetch XML you have not assigned #contactid# in the condition attribute. I have rewrite your fetchXML  , you just need to assign the GUID of contactid. Hope this helps.

    Try with this -

    var contactid = "00000000-0000-0000-00AA-000010001001" // You need to assign the GUID of contact Id for example -- Xrm.Page.getAttribute("contactid").getValue()[0].id
    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>" +
      "<entity name='va_incident'>" +
        "<attribute name='va_incidentid' />" +
        "<attribute name='va_name' />" +
        "<order attribute='va_name' descending='false' />" +
        "<link-entity name='va_va_incident_contact' from='va_incidentid' to='va_incidentid' visible='false' intersect='true'>" +
          "<link-entity name='contact' from='contactid' to='contactid' alias='ac'>" +
            "<filter type='and'>" +
              "<condition attribute='contactid' operator='eq' value='" + contactID + "' />" +
            "</filter>" +
          "</link-entity>" +
        "</link-entity>" +
      "</entity>" +
    "</fetch>";
    
    var encodedFetchXml = encodeURI(fetchXml);
    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/va_incidents?fetchXml=" + encodedFetchXml, true);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                var results = JSON.parse(this.response);
                for (var i = 0; i < results.value.length; i++) {
                    var va_incidentid = results.value[i]["va_incidentid"];
                    var va_name = results.value[i]["va_name"];
                    var lookupValue = new Array();
                    lookupValue[0] = new Object();
                    lookupValue[0].id = va_incidentid;  // Guid Of That Look Up
                    lookupValue[0].name = va_name;       // Name  Of That Look Up
                    lookupValue[0].entityType = "va_incident";    // Entity Name Of That Look Up
                    Xrm.Page.getAttribute("va_incidentid").setValue(lookupValue);
                }
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();


  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Autopopulate Lookup when only one value exists

    I received an internal server error message, have no idea how to debug it.  The problem is how to set the Current Contact Id

    var fetchXml = "<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"true\">" +
      "<entity name=\"va_incident\">" +
        "<attribute name=\"va_incidentid\" />" +
        "<attribute name=\"va_name\" />" +
        "<order attribute=\"va_name\" descending=\"false\" />" +
        "<link-entity name=\"va_va_incident_contact\" from=\"va_incidentid\" to=\"va_incidentid\" visible=\"false\" intersect=\"true\">" +
          "<link-entity name=\"contact\" from=\"contactid\" to=\"contactid\" alias=\"ac\">" +
            "<filter type=\"and\">" +
              "<condition attribute=\"contactid\" operator=\"eq\" value=\"#contactid#\" />" +
            "</filter>" +
          "</link-entity>" +
        "</link-entity>" +
      "</entity>" +
    "</fetch>";
    var encodedFetchXml = encodeURI(fetchXml);
    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/va_incidents?fetchXml=" + encodedFetchXml, true);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function() {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                var results = JSON.parse(this.response);
                for (var i = 0; i < results.value.length; i++) {
                    var va_incidentid = results.value[i]["va_incidentid"];
                    var va_name = results.value[i]["va_name"];
                   var lookupValue = new Array();
                   lookupValue[0] = new Object();
                   lookupValue[0].id = va_incidentid;  // Guid Of That Look Up
                   lookupValue[0].name = va_name;       // Name  Of That Look Up
                   lookupValue[0].entityType = "va_incident";    // Entity Name Of That Look Up
                   Xrm.Page.getAttribute("va_incidentid").setValue(lookupValue);
                }
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();
  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Autopopulate Lookup when only one value exists

    I looked at the article, but I do not understand it.  Where would I put that code to run?  I am very, very, very, new to CRM.  I have put in forms and relationships, but ZERO coding in it.  I have the Fetch XML and the Web API code.   That example code in the link does not appear to be JavaScript.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Autopopulate Lookup when only one value exists

    When trying to use the Fetch XML, I went into my Entity A and could not find the Contacts in related entities, even though I created the N:N relationship, so I am not sure what Fetch XML I want to generate, since I am seeking a list of Entity A(s) associated with the current Contact. 

    I was able to figure out that I needed to set the Relationship to visible.  Now when I open the Advanced Find, I can choose Contacts, but there is no option to set the Current Contact.

  • Verified answer
    Aric Levin Profile Picture
    Aric Levin 30,188 on at
    RE: Autopopulate Lookup when only one value exists

    Hi Marsox,

    As you are going to need to use Web Api to retrieve this information, I recommend that you download CRM Rest Builder in order to help you generate Api calls and retrieve the results that you want.

    github.com/.../CRMRESTBuilder

    After you get the results, you should be able to use the code that Goutam specified below.

    Hope this helps.

  • gdas Profile Picture
    gdas 50,085 on at
    RE: Autopopulate Lookup when only one value exists

    Hi Marsox,

    When you retrieve the lookup data using fetch XML you can count whether there is one value or multiple value. Based on that you can set the value.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Autopopulate Lookup when only one value exists

    Thank you.  The lookup may not always have just one value. I only want to set it when there is one value in it.

  • gdas Profile Picture
    gdas 50,085 on at
    RE: Autopopulate Lookup when only one value exists

    Hi Marsox,

    As lookup field does not contain default value so you need get the value first using fetchXML of the particular lookup entity.

    You can check below reference how to retrieve data using fetch XML.

    https://community.dynamics.com/crm/b/mscrmcustomization/archive/2016/11/01/use-fetchxml-to-retrieve-data-from-ms-crm-2016-using-web-api

    You can build your fetchXML by using Advanced find in CRM.

    Once you retrieve the data from lookup entity you can set field value by below way.

    function setLookUp(){
    
                   var lookupValue = new Array();
                   lookupValue[0] = new Object();
                   lookupValue[0].id = "16C0C201-F1B9-E111-9361-B8AC6F88836B";  // Guid Of That Look Up
                   lookupValue[0].name = "Client";       // Name  Of That Look Up
                   lookupValue[0].entityType = "contact";    // Entity Name Of That Look Up
                   Xrm.Page.getAttribute("new_jobcentrecontacttype").setValue(lookupValue);
    }


    Hope this helps.

  • Aric Levin Profile Picture
    Aric Levin 30,188 on at
    RE: Autopopulate Lookup when only one value exists

    Hi Marsox,

    There is no default value option for a lookup. This is something that you would have to customize in the system, and as you already can imagine, it can be done using one of the methods that you are looking for.

    I would suggest using webapi to retrieve the value of the that you are looking for, and then calling the setValue function of the attribute class (Xrm.Page.getAttribute(attributeName).setValue(lookupValue))

    I am not sure if there is a third party solution that will enable you to do this automatically. Haven't seen one.

    I hope you get a different answer, but I doubt there is.

    Good luck.

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,253 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans