Java Script to get Business Unit of currently logged in user

This post is to show how you can get the Business Unit of currently logged in User in Dynamics CRM

Step 1: Upload Jquery.min.js file as JScript web resource on the entity form.

Step 2: Upload Json2.js file as JScript web resource on the entity form.




Step 3: Create a new web resource of type JScript.

Step 4: Paste the below code in it.

function getBU()
{
    var id = Xrm.Page.context.getUserId(); //Get id of current user
var businessUnit; //Variable to hold business unit object
var odataSelect = Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/SystemUserSet?$select=BusinessUnitId&$filter=SystemUserId eq guid'" + id + "'"; //Write odata query here
    if (id != null )
{
        $.ajax
(
{
type: "GET", //Get method is used to fetch data from Dynamics CRM
async: false,
contentType: "application/json; charset=utf-8", //Type of content
datatype: "json", //Data type
url: odataSelect, //Odata query
beforeSend: function (XMLHttpRequest)
{
//Specifying this header ensures that the results will be returned as JSON
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest)
{
businessUnit = data.d.results[0].BusinessUnitId; //Store BU object
var id = businessUnit.Id; //Set BU id in id
var name = businessUnit.Name; //Set BU name in name
alert("The business unit name:  " + name + "\nThe business unit ID:  " + id);
},
error: function (XmlHttpRequest, textStatus, errorThrown)
{
alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect);
}
}
);
    }
}

Step 5: Attach the web resource wherever you want, either on the page or on any button.

Comments

Popular posts from this blog

Creating a Grid dynamically using HTML in Dynamics CRM to show, update and delete associated records in an entity