如何使用 JavaScript 在 Dynamics 365 CRM 内部部署的表单上填写父查询?

How to use JavaScript to fill parent lookup on form in Dynamics 365 CRM on-premise?

假设我有 3 个相关实体 (PhoneCall-Account-Contact)。有关详细信息,我必须在电话表格中说我有一个与帐户相关的自定义查找字段,另一个与联系人相关,最后一个再次与用于父帐户的帐户相关。现在我想要一个解决方案,当我在用正确的数据填充父帐户查找之后填充帐户字段时,或者如果我首先用正确的数据填充联系人查找,然后用正确的数据填充父帐户字段,我想要一个解决方案。我搜索了很多方法,但我找不到任何方法来找到正确的父帐户并填写我的查找,即使我使用业务规则也无法帮助我。

现在我在很多网站上看到建议使用CRM REST BUILDER。我用过,但没能解决我的问题。

您需要的是一个 Javascript 函数来触发第一次查找的更改,以从父记录中查询必要的字段并将其填写到当前的子记录表单中。 Read more

function fillParentAccount() {

var lookup= Xrm.Page.getAttribute("accountfieldname").getValue();  //you will get the id with exxtra double quotes or square brackets by doing get value hence you to make it readable by CRM , you must slice it. i have use the below method:
var newid = lookup[0].id.slice(1, -1);  // you will get perfect id like "EDCJDKDJDKJDJDKJDJKD" here.
var req = new XMLHttpRequest(); //once you have the id , you have frame to make a webapi GET call by proving the newid we got.

req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.1/accounts(" + newid + ")?$select=_parentaccountfieldname_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) {
req.onreadystatechange = null;
if (this.status === 200) {
var result = JSON.parse(this.response); // you will get the retrieved value in object we stored in result var.
var retrivedvalue= result._parentaccountfieldname_value; //get the id of the field
var retrivedformatedvalue= result["_parentaccountfieldname_value@OData.Community.Display.V1.FormattedValue"]; //get the formatted name of the field
if (retrivedvalue!= null) {
var value = new Array();
value[0] = new Object();
value[0].id = retrivedvalue;
value[0].name = retrivedformatedvalue;
value[0].entityType = "account";
Xrm.Page.getAttribute("parentaccountfield").setValue(value); //set the lookup value finally
}
else
alert("some textt!!!!!!") // optional
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();

确保更改字段名称和自定义的准确性。