All about client side Scripting(.js) in Dynamics 365 CRM

Microsoft CRM Basic JavaScript for Field level and other changes.

Note: As of now, Microsoft has deprecated the below format of Xrm.Page from dynamics 365 version V9  with ‘ExecutionContext.getFormContext ‘ but you can still use them as it is still not removed from the older versions of CRM for more details visit our page Useful links and scroll down to Important changes in MSCRM.

Below is the new Dynamics Client API hierarchy.
formContext object model

For Newer version (v9 and ahead) Js Code, do follow the link Click here.
or you can just replace ‘Xrm.Page’ with ‘executionContext.getFormContext()’

//To check if Dynamics XRM javascript is being invoked 
//from the unified interface (UCI) or the legacy web-client?
 function isUCI() {
   var globalContext = Xrm.Utility.getGlobalContext();
   var t1 = globalContext.getCurrentAppUrl();
   var t2 = globalContext.getClientUrl();
   return t1 !== t2;

//Code to write Right to Left
document.getElementById('mo_arabicsummary').style.direction = 'rtl';

//Code for hiding tab in MSCRM  using javascript

//code for hiding section

//Code for retrieving field value in MSCRM using javascript

//code to set required field
Xrm.Page.getAttribute("fieldname").setRequiredLevel("required"); //none //recommended

//Code to disable enable a field
Xrm.Page.getControl("fieldname").setDisabled(true); //true/false

//Code to add value in a locked field using javascript"fieldname").setSubmitMode("always");
//If your field is locked and if you are trying to change or add value to that field it will get omitted while saving the form unless you don't use the above piece of code just after setting the value to the field.

//Code for Page navigation

//Code for hiding Field

//Code to get DialogueBox
function rec() {
    Xrm.Utility.confirmDialog("Message Student Got Selected", function () {
        Xrm.Page.getAttribute("new_comments").setValue("Student Selected");
    }, function () {
        Xrm.Page.getAttribute("new_comments").setValue("Student Not selected");

//Code to add form level Notification as a bar in MSCRM using Javascript
//This code also can be used for mobileNo validation for 10 digit number
function mobilephone_OnChange() {
    var Mobileno = Xrm.Page.getAttribute("mobilephone").getValue();
    if (Mobileno != null) {
        var mobeg = /[^0-9\+]+/;
        if (mobeg.test(Mobileno) == true || Mobileno.length != 10) {
            Xrm.Page.ui.setFormNotification("Enter only 10 digit Mobile Number", "ERROR", "MobileNumber");
        else {

//Code to get current loggedIn UserId
var userID = Xrm.Page.context.getUserId();

//Code to Check user roles in MSCRM using Javascript
//Returns in boolean(true / false)
var currentUserRoles = XrmServiceToolkit.Soap.IsCurrentUserRole("System Adminstrator");

//Code to set Lookup field value.
var lookup = new Array();
lookup[0] = new Object();
lookup[0].id = userID; //Id of the entity whose lookup you want to set
lookup[0].name = recordname; // name field value of the entity.
lookup[0].entityType = "systemuser";//put the entity logical name here 

//Or other way to set value of a lookup field.
    Xrm.Page.getAttribute("fieldname").setValue([{ id:, name:, entityType: team.logicalName }]);

//Code to get the Id and Name from a lookup field in MSCRM using Javaacript
var regardingId = Xrm.Page.getAttribute("regardingobjectid").getValue() != null ? Xrm.Page.getAttribute("regardingobjectid").getValue()[0].id : null;

//Will give you the Id.
var regardingName = Xrm.Page.getAttribute("regardingobjectid").getValue() != null ? Xrm.Page.getAttribute("regardingobjectid").getValue()[0].name : null; 

//Will give you the Name.

//Code to Set Value to a date field
var d = new Date();
var date = new Date(d.getFullYear(), d.getMonth(), d.getDate());

//Code to refresh page in MSCRM using javascript;

//Code to get FormType of an Entity Record
//Return Value
//Type: Number
//The following table lists the form types that correspond to the return value.
//Value Form Type
//0 - Undefined
//1 - Create(New Form)
//2 - Update(Already saved form)
//3 - Read Only
//4 - Disabled
//5 - Quick Create(Deprecated)
//6 - Bulk Edit

//Code to SAVE a record in MSCRM using Javascript.;
//Saves and open new form in the entity.'saveandnew');
//Save and Close the entity form'saveandclose');

//Code to prevent page save in MSCRM using Javascript
function BlockSaveAfterCreate(event) {
    var formType = Xrm.Page.ui.getFormType();
    if (formType != 1) {
        alert("This is already a saved form!")

//Get Current Record ID (getID) current Record GUID
var entityId =;

//Retrieve all option-Set values with label-text and values.
function getOptionDetails() {
      var optionDetails = Xrm.Page.getAttribute("SchemaNameofOptionsetField").getOption(); 
      if (optionDetails != null) {
           //To get text of the option set.
           var optionText = optionDetails.getText();
var optionValue = optionDetails.getValue();
           alert("OptionSet Text and value:" + optionText+ ","+optionValue );

//Set Focus in Crm. You can bring either Tabs or Field in focus on form using SetFocus()


//New Syntax for UCI forms
//Get the Microsoft Dynamics entity record GUID using the formContext in JavaScript

//Other client side statement similar to getId

//CRM Code to read Subgrid rows
function ReadSubgrid (executionContext) {
	var formContext = executionContext.getFormContext();

	//Get Subgrid Control.
	var gridControl = formContext.getControl("Subgrid_control");
	// if the subgrid still not available we try again after 1 second
    if (gridControl == null) {
        setTimeout(function () {  ReadSubgrid(executionContext); }, 1000);
	//Collecting Subgrid Rows.
	var subgridRows = gridControl.getGrid().getRows();
	//Obtaining Total Row Count.
	var subgridRowCount = subgridRows.getLength();
	//Iterating Through Subgrid Rows.
	for (var i = 0; i < subgridRowCount; i++) {
		//Loop through each Subgrid rows
		var subgridRowData = subgridRows.get(i).getData();
		//Obtaining Row Entity Object.
		var entity = subgridRowData.getEntity();
		//Collecing Row EntityRefrence.
		var entityReference = entity.getEntityReference();
		//store  entity name  In A Variable.
		var name +=;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s