Get the business unit name of the logged-in user

1 min read

Summary

This code snippet illustrates how to get the business unit details of the logged-in user. This is great for certain use cases that require form conditions based on who has logged into Dynamics 365.

Two additional libraries are required:

Json2.js and SDK.REST.js

Both these libraries can be found in the Microsoft Dynamics 365 SDK.

The code

//Gets the current users Business Unit Name
//Requires JQuery.js & JSON2.js

function GetBusinessUnit() {

    var roleId = Xrm.Page.context.getUserId();
    var serverUrl = location.protocol + "//" + location.host + "/";
    var businessUnitName;
    var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/SystemUserSet?$select=BusinessUnitId&$filter=SystemUserId eq guid'" + roleId + "'";
    $.ajax({
        type: "GET",
        async: false,
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: odataSelect,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            businessUnitName = data.d.results[0].BusinessUnitId.Name;
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect);
        }
    });
    return businessUnitName;
}

You must be logged in to post a comment.