Untitled

 avatar
unknown
plain_text
a year ago
2.0 kB
7
Indexable
function fillEmployer() {
  var lookup = Xrm.Page.getAttribute("customerid").getValue();
  
  if (!lookup || lookup.length === 0) {
    console.error("No customer ID found.");
    Xrm.Page.getAttribute("bh_employer").setValue(null); // Set bh_employer to null
    return;
  }

  var newId = lookup[0].id.slice(1, -1); // Extract the ID without extra quotes or brackets

  var req = new XMLHttpRequest();
  req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.1/accounts(" + newId + ")?$select=_bh_employer_value", 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) {
      if (this.status === 200) {
        var result = JSON.parse(this.response);
        var retrievedValue = result._bh_employer_value;
        var retrievedFormattedValue = result["_bh_employer_value@OData.Community.Display.V1.FormattedValue"];

        if (retrievedValue) {
          var value = [{
            id: retrievedValue,
            name: retrievedFormattedValue,
            entityType: "account"
          }];
          Xrm.Page.getAttribute("bh_employer").setValue(value);
        } else {
          Xrm.Page.getAttribute("bh_employer").setValue(null); // Set bh_employer to null if no value is retrieved
        }
      } else {
        console.error("Error fetching employer data: " + this.status + " " + this.statusText);
        Xrm.Page.getAttribute("bh_employer").setValue(null); // Set bh_employer to null on error
      }
    }
  };

  req.onerror = function () {
    console.error("Request failed");
    Xrm.Page.getAttribute("bh_employer").setValue(null); // Set bh_employer to null on request failure
  };

  req.send();
}
Editor is loading...
Leave a Comment