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
Xrm.Page.ui.tabs.get("tab_2").setVisible(false);

//code for hiding section
Xrm.Page.ui.tabs.get("tab_2").sections.get("section_1").setVisible(true);

//Code for retrieving field value in MSCRM using javascript
Xrm.Page.getAttribute("fieldname").getValue();

//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
Xrm.Page.data.entity.attributes.get("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
Xrm.Utility.openEntityForm("entityschemaname");

//Code for hiding Field
Xrm.Page.getControl("fieldname").setVisible(false);

//Code to get DialogueBox
rec();
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");
            Xrm.Page.getAttribute("mobilephone").setValue();
        }
        else {
            Xrm.Page.ui.clearFormNotification("MobileNumber");
        }
    }
}

//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 
Xrm.Page.getAttribute("ownerid").setValue(lookup);

//Or other way to set value of a lookup field.
    Xrm.Page.getAttribute("fieldname").setValue([{ id: team.id, name: team.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());
Xrm.Page.getAttribute("fieldname").setValue(date);

//Code to refresh page in MSCRM using javascript
Xrm.Page.data.refresh();

//Code to get FormType of an Entity Record
Xrm.Page.ui.getFormType()
//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.
    Xrm.Page.data.entity.save();
//Saves and open new form in the entity.
    Xrm.Page.data.entity.save('saveandnew');
//Save and Close the entity form
Xrm.Page.data.entity.save('saveandclose');

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

//Get Current Record ID (getID) current Record GUID
var entityId = Xrm.Page.data.entity.getId();

//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()

Xrm.Page.ui.tabs.get("tab_2").setFocus();
Xrm.Page.getControl("prm_rockwellcontact1").setFocus()

//New Syntax for UCI forms
formContext.getControl(arg).setFocus();
//Get the Microsoft Dynamics entity record GUID using the formContext in JavaScript 
formContext.data.entity.getId

//Other client side statement similar to getId
formContext.data.entity.addOnSave formContext.data.entity.getDataXml
formContext.data.entity.getEntityName
formContext.data.entity.getEntityReference
formContext.data.entity.getIdgetIsDirty
formContext.data.entity.getPrimaryAttributeValue
formContext.data.entity.isValid
formContext.data.entity.removeOnSave

formContext.data.entity.save

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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