Hi R T,
Considering your code async mode how it will run -
Step 1:
Execution Start Here - time 12:01 PM
Function GetUserFirstName (UserID) {
Step 3:
Execution Start Here - time 12:03 PM [Due to asynchronous mode you can not received the first name here]
if (Firstname == "Fred") {
do something // disable a field, etc .
}
Step 2:
Execution Start Here - time 12:02 PM
/// xmlhttprequest in async mode here
Step 4:
Received First Name - time 12:05 PM
return json data - firstname
}
So to handle this you should call your function inside onreadystatechange or onload of the XMLHttpRequest async call.
Step 1:
Execution Start Here - time 12:01 PM
Function GetUserFirstName (UserID) {
Step 2:
Execution Start Here - time 12:02 PM
call xmlhttprequest in async mode here
Step 3:
Received First Name - time 12:05 PM
json data - firstname
You should write the call back inside the method when you get the result.
Step 4:
Execution Start Here - time 12:06 PM [Due to asynchronous mode need to write call back logic after received the result]
if (Firstname == "Fred") {
do something // disable a field, etc .
}
In Summary here is the detail code will be look like -
GetFirstName();
function GetFirstName() {
var resstatus;
var id = Xrm.Page.data.entity.getId();
var getIDD = id.substr(1, id.length - 2);
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/contacts?$filter=contactid eq (" + getIDD + ")", 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.send();
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var result = JSON.parse(this.response);
var firstName = result["firstname"];
callbacToSetFirstName(firstName);
}
}
else {
}
};
return resstatus;
}
function callbacToSetFirstName(firstName)
{
Xrm.Page.getAttribute('new_name').setValue(firstName);
}
Hope this helps.