Java-Script (MS Dynamic CRM)

Here is the list of JS which are used in MS Dynamic CRM

#To check the Client: 
 var client = Xrm.Page.context.client.getClient();

 if (client == "Mobile") {
   // write code for Mobiles / Tablets device
 }
 if (client == "Web")  {
   // Write code for Web browser / desktop
 }

#Get value of fields:
*To get value of fields like Text/Decimal/Float/Currency/Whole No:
  Xrm.Page.getAttribute("FieldName").getValue();

*To get value of Look Up Field:
For ID:  Xrm.Page.getAttribute("FieldName").getValue()[0].id;
For Name:  Xrm.Page.getAttribute("FieldName").getValue()[0].name;
For EntityType: Xrm.Page.getAttribute("FieldName").getValue()[0].entityType;

*To get value of field like Option set/Boolean:
 For Text: Xrm.Page.getAttribute("FieldName").getText();
 For Value: Xrm.Page.getAttribute("FieldName").getValue();

*To get value of Multiple option set (available in D365 v9.0 ) :
For Value: Xrm.Page.getAttribute("FieldName").getValue()[indexValue];
For Text: Xrm.Page.getAttribute("FieldName").getText()[indexValue];
// indexValue can be 0,1,2......

#Set value of fields:
*To set value of fields like Text/Decimal/Float/Currency/Whole No:
  Xrm.Page.getAttribute("FieldName").setValue("value");

*To set value of Boolean field type:
  Xrm.Page.getAttribute("FieldName").setValue(true/false);

*To set value of Option set field type:
  Xrm.Page.getAttribute("FieldName").setValue(100000000);

*To set LookUp field type:
var lookUp = new Array();
lookUp[0] = new Object();
lookUp[0].id = recordId;
lookUp[0].name = recordName;   // this is optional
lookUp[0].entityType = entityName;
 Xrm.Page.getAttribute("FieldName").setValue(lookUp);

*To set value of Multiple option set value:   Xrm.Page.getAttribute("FieldName").setValue([100000000,100000001]);

#Check field is mandatory or not:
  var value = Xrm.Page.getAttribute("FieldName").getRequiredLevel();
value would be required or none. if required, it means field is mandatory. if none, it means field is not mandatory.

#Make a field mandatory / remove mandatory:
Xrm.Page.getAttribute("FieldName").setRequiredLevel("required");
Xrm.Page.getAttribute("FieldName").setRequiredLevel("none");

#Check Visibility of a field:
var value = Xrm.Page.getControl("FieldName").getVisible();
value would be true or false. if true, it mean field is visible. if false, it mean field is not visible.

#Show/Hide field:
Xrm.Page.getControl("FieldName").setVisible(true/false);

#Check Visibility of a Section:
var value = Xrm.Page.ui.tabs.get("Tab_Name").sections.get("Section").getVisible();
value would be true or false. if true, it mean section is visible. if false, it mean section is not visible.

#Show/Hide Section:
Xrm.Page.ui.tabs.get("Tab_Name").sections.get("Section").setVisible(true/false);


#Check Visibility of a Tab:
var value = Xrm.Page.ui.tabs.get("Tab_Name").getVisible();
value would be true or false. if true, it mean tab is visible. if false, it mean tab is not visible.

#Show/Hide Tab:
Xrm.Page.ui.tabs.get("Tab_Name").setVisible(true/false);


#Get Display State of Tab:
  var State = Xrm.Page.ui.tabs.get("tab_Name").getDisplayState();
  State would either be collapsed or expanded.

#Set Display State of Tab:
  var State = "expanded" OR "collapsed" ;
  Xrm.Page.ui.tabs.get("tab_Name").setDisplayState(State);

#Check Field is Enable/Disable (read only):
var value = Xrm.Page.getControl("FieldName").getDisabled();
value would be true or false. if true, it mean field is disabled. if false, it mean field is not disabled.

#Enable/Disable field (read only):
Xrm.Page.getControl("FieldName").setDisabled(false/true);


#Disable/Enable Section (read only):
function disableSection(sectionName){
var controls = Xrm.Page.ui.tabs.get("tabName").sections.get(sectionName).controls.get();
var numberOfControls = controls.length;  
for (var i = 0; i < numberOfControls; i++) {
        controls[i].setDisabled(true/false);
 }
}

#Enable/Disable Tab (read only):

var Tab =  Xrm.Page.ui.tabs.get("tabName");
var Sections =  Tab.sections.get();
for (var i in Sections) {
      var sectionName = Sections[i].getName();
      disableSection(sectionName); 
 }

function disableSection(sectionName){
var controls = Xrm.Page.ui.tabs.get("tabName").sections.get(sectionName).controls.get();
var numberOfControls = controls.length;  
for (var i = 0; i < numberOfControls; i++) {
        controls[i].setDisabled(true/false);
 }
}

#Enable/Disable Form (read only):

Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
            var control = Xrm.Page.getControl(attribute.getName());
            if (control) {
                control.setDisabled(false/true);
    }
});

                                    OR

function setFormAsReadOnly() {
    //Write you conditions here.
    disableFormFields(true);
}

function disableFormFields(onOff) {
    Xrm.Page.ui.controls.forEach(function (control, index) {
        if (doesControlHaveAttribute(control)) {
            control.setDisabled(onOff);
        }
    });

}

function doesControlHaveAttribute(control) {
    var controlType = control.getControlType();
    return controlType != "iframe" && controlType != "webresource" && controlType != "subgrid";
}

#To Get Organization URL: 
   Xrm.Page.context.getClientUrl();

#To Get the Version of Organizaion:
   Xrm.Page.context.getVersion();

#To Get the Log-in UserName:
   Xrm.Page.context.getUserName();

#To Get the GUID of Log-in User:
   Xrm.Page.context.getUserId();

#To Get the GUID of Roles of Current Log-in User:
   Var rolesIdArray = Xrm.Page.context.getUserRoles();

#To Get the Roles of Current Log-in User:
for (var i = 0; i < rolesIdArray.length; i++) {
                var userRoleId = rolesIdArray[i];
var userRoleName = GetRoleName(userRoleId);
alert(userRoleName);
 }

function GetRoleName(roleId) {
var roleName="";
    var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/roles("+roleId+")?$select=name", false);
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=\"*\"");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 200) {
            var result = JSON.parse(this.response);
             roleName = result["name"];

        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send();
return roleName;
}


#To save the form:
   Xrm.Page.data.entity.save();

#To Get the Entity name:
   var value = Xrm.Page.data.entity.getEntityName();

#To Get GUID of a current record:
    var value = Xrm.Page.data.entity.getId();

#To open new entity form:
    Xrm.Utility.openEntityForm("entityName");   
   // For Example : Xrm.Utility.openEntityForm("account");

#To open an existing record:
    Xrm.Utility.openEntityForm( "entityName" , "recordID" );    
   // For Example : Xrm.Utility.openEntityForm( "account" , "B85C0252-DF8B-E111-997C-00155D8A8410" );

#Open a new entity with a specific Form:
   var parameters = {};   
   parameters["formid"] = formGUID("formName") ;   // This is a function which is defined below.
   //  parameters["formid"] = "b053a39a-041a-4356-acef-ddf00182762b" ;    
  Xrm.Utility.openEntityForm("entityName" , null , parameters);  
  
 NOTE : Here "null" signify that we are opening a new form. 

#Open a new Entity record using the default form in a new window:
   var windowOptions = { openInNewWindow: true };   
   Xrm.Utility.openEntityForm("entityName" , null , null ,windowOptions); 

#Get Current Form Name and GUID of entity:
    var currentFormName = Xrm.Page.ui.formSelector.getCurrentItem().getLabel();    
    var currentFormID = Xrm.Page.ui.formSelector.getCurrentItem().getId();

#To Get Form GUID:
  function formGUID(formName){
    var allForm = Xrm.Page.ui.formSelector.items.get();   // or  Xrm.Page.ui.formSelector.getItems().getAll();
    for(var i=0 ; i < allForm.length ;i++){
      var getFormName = allForm[i].getLabel();
      if(getFormName == formName){
         return allForm[i].getId();
      }
    }
  }

#To Get Entity Type Code:
    var Code = Mscrm.EntityPropUtil.EntityTypeName2CodeMap["EntityName"];   
  // For Example : var Code = Mscrm.EntityPropUtil.EntityTypeName2CodeMap["contact"];

#To open a specific record using hyperlink or URL:
    var orgName = window.parent.Xrm.Page.context.getClientUrl();   
   var entityCode = Mscrm.EntityPropUtil.EntityTypeName2CodeMap["EntityName"]; 
    recordURL = orgName + "/main.aspx?etc=" + entityCode + "&extraqs=&histKey=850858799&id={" + RecordGUID + "}&newWindow=true&pagetype=entityrecord" ;  
   window.open(recordURL);  
   // This kind of URL used in web-resources.

#Open a window like a Pop-Up:
    window.open(URL, "myWindow", 'width=720,height=350,top=150,left=350');

#Encode the URL:
    var En_URL = encodeURIComponent(URL);

#Decode the URL:
    var De_URL = decodeURIComponent(URL);

#Business Process Flow(BPF) Java-Scripts:

#Get BPF's / Process's  ID:
   var value = Xrm.Page.data.process.getActiveProcess().getId();

#Get BPF's / Process's  Name:
   var value = Xrm.Page.data.process.getActiveProcess().getName();

#Get Visibility of a process:
   var value = Xrm.Page.ui.process.getVisible();

#Set Visibility of a process:
   var value = Xrm.Page.ui.process.setVisible(false/true);

#Get Display State of a process:
   var value = Xrm.Page.ui.process.getDisplayState();
          it can either be collapsed or expanded

#Set Display State of a process:
   var value = "collapsed"  or "expanded"
     Xrm.Page.ui.process.setDisplayState(value);

#Get Active Stage Name of a process:
   var value = Xrm.Page.data.process.getActiveStage().getName()

#Get Active Stage ID of a process:
   var value = Xrm.Page.data.process.getActiveStage().getId()

#Call a function when BPF's stages change or call a function when we click on Next Stage:
   Xrm.Page.data.process.addOnStageChange(function name);


#To open confirmation pop-up:
    var yes/no = window.confirm('Do you want to execute?');

#To refresh the Home View Grid:
   document.getElementById("refreshButtonLink").click();
                                          OR
   document.getElementById("crmGrid").control.refresh();

#To refresh the form's data after some changes on form:
    Xrm.Page.data.refresh(); 

3 comments:

Kani Mozhi said...

This site has lots of advantage. I found many interesting things from this site. It helps me in many ways.Thanks for posting this again.
CRM Software in Dubai
CRM Software
CRM Software in UAE
Best CRM Software in Dubai

Bala Vignesh said...

Great and really helpful article! Adding to the conversation, providing more information, or expressing a new point of view...Nice information and updates. Really i like it and everyday am visiting your site..
CRM Software In India
CRM Software In Chennai
CRM Software
CRM Software In Bangalore
Best CRM Software

raghu said...


This is a really informative blog, I have to thank you for your efforts. Waiting for more posts like this.
Ethical Hacking Course in Chennai
Ethical Hacking Online Course
Ethical Hacking Course in Coimbatore