Showing posts with label Web API in CRM. Show all posts
Showing posts with label Web API in CRM. Show all posts

Friday, December 23, 2016

Web API in MS CRM 2016

//Used to set Line of Business on create of Account record (Fetch LOB from the User Entity)
function onLoadSetLineOfBusiness(LineofBusiness) {
    var logInUser = Xrm.Page.context.getUserId();
    var retrieveRecordsReq = new XMLHttpRequest();
    var serverUrl = Xrm.Page.context.getClientUrl();
    // Adjust URL for differences between on premise and online
    if (serverUrl.match(/\/$/)) { serverUrl = serverUrl.substring(0, serverUrl.length - 1); }

    //Web API Calls
    var req = new XMLHttpRequest();
    if (logInUser != null && logInUser != "") {
        req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/systemusers?$select=_new_lineofbusiness_value&$filter=systemuserid eq " + logInUser.replace('{', '').replace('}', '') + "", 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=\"OData.Community.Display.V1.FormattedValue\"");
        req.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 200) {
                    var LOBName = JSON.parse(this.response);
                    if (LOBName.value.length > 0) {
                        //to set the LookUp Value we have to use Formatted Value
                        if (LOBName.value[0]._new_lineofbusiness_value != null && LOBName.value[0]._new_lineofbusiness_value != "") {
                            var LOBvalue = new Array();
                            LOBvalue[0] = new Object();
                            LOBvalue[0].id = LOBName.value[0]._new_lineofbusiness_value;
                            LOBvalue[0].name = LOBName.value[0]['_new_lineofbusiness_value@OData.Community.Display.V1.FormattedValue'];
                            LOBvalue[0].entityType = "new_business";
                            Xrm.Page.getAttribute(LineofBusiness).setValue(LOBvalue);
                            Xrm.Page.getAttribute(LineofBusiness).setSubmitMode("always");
                        }
                    }
                }
                else {
                    alert(this.statusText);
                }
            }
        };
        req.send();
    }
}