JavaScript Function for Reference

This blog will guide you with the JavaScript functions which are most common in use. These functions are ready to use and are tested on account entity.

Content:

  1. Get text value
  2. Set text value
  3. Get option set label
  4. Get option set value
  5. Set option set label
  6. Set multi option set label
  7. Get lookup GUID/text value
  8. Set lookup field
  9. Get date, month and year value from date field
  10. Set date field value
  11. Get current User ID/Name
  12. Get current record ID
  13. Get User Security role
  14. Set field requirement
  15. Show/hide field
  16. Show/hide section
  17. Show/hide tab
  18. Save form
  19. Save and close form
  20. Prevent save
  21. Get Dirty fields
  22. Get CRM URL
  23. Set lookup window view
  24. Change form view
  25. Pop up quick create form
  26. Pop up entity blank form
  27. Pop up entity form with data
  28. Pop up record
  29. Confirm/Cancel dialog
  30. Pop up web resource
  31. Retrieve data using CRM REST APIs
  32. Retrieve data using fetch XML

1. Get text value:

This function will get the text value of the “account name” from account entity.

function GetText(context) {
    var txtVal = context.getFormContext().getAttribute("name").getValue();
}

2. Set text value:

This function will set the text value of the “account name” in account entity.

function SetText(context) {
    context.getFormContext().getAttribute("name").setValue("MSCRMWITHRamandeep");
}

3. Get option set label:

This function will get the option set label of the “Relationship type” from account entity. Example: Competitor

function GetOptionSetLabel(context) {
   var customertypeText = context.getFormContext().getAttribute("customertypecode").getText();
    if (customertypeText != null) {
        //code here
    }
}

4. Get option set Value:

This function will get the option set label of the “Relationship type” from account entity.

Example Value : 1
function GetOptionSetValue(context) {
   var customertypeTextValue = context.getFormContext().getAttribute("customertypecode").getValue();
    if (customertypeTextValue != null) {
        //code here
    }
}

5. Set option set label:

This function will set the option set label of the “Relationship type” in account entity.

function SetOptionSetField(context) {
    context.getFormContext().getAttribute("customertypecode").setValue(1);
}

6. Set multi option set label:

This function will set the multi option set label of a custom field in account entity record.

function SetMultiSelect(Context) {
   var formContext = Context.getFormContext();
   formContext.getAttribute("new_democrm").setValue([100000000,100000001,100000002]);
}

7. Get lookup GUID/text value:

This function will get the GUID and text values of a lookup field from account entity record.

function LookUpValue(context) {
   var formContext = context.getFormContext();
   if(formContext.getAttribute("primarycontactid") != null)
   {
   	var LookUPGUID = formContext.getAttribute("primarycontactid").getValue()[0].id;
	var LookUPText = formContext.getAttribute("primarycontactid").getValue()[0].name;
   }
}

8. Set lookup field:

This function will set the lookup field by using record Id, full name and entity type.

function SetLookUpValue(context) {
   var formContext = context.getFormContext();
   var lookupValue = new Array();
   lookupValue[0] = new Object();
   lookupValue[0].id = "{E604703C-63CD-E911-A812-000D3A0A82A5}";
   lookupValue[0].name = "Jim Glynn (sample)";
   lookupValue[0].entityType = "contact";
   context.getFormContext().getAttribute("primarycontactid").setValue(lookupValue);
}

9. Get date, month and year value from date field:

This function will get the date, month and year from the date field.

function GetFormatDate(context) {
   var formContext = context.getFormContext();
   var dateVal = formContext.getAttribute("new_date").getValue();
    if (dateVal != null) {
     var date = dateVal.getDate();
     var month = dateVal.getMonth();
     month++;  // Jan = 0 so got to use ++
     var year = dateVal.getFullYear();
    }
}

10. Set date field value:

This function will set the date to today for date field. This will work for Date and DateTime format.

function SetDateField(context) {
   var formContext = context.getFormContext();
   formContext.getAttribute("new_date").setValue(new Date());
}

11. Get current user ID/Name:

This function will get Current user ID and name.

function CurrentUserId(context) {
   var formContext = context.getFormContext();
   var UserGUID = formContext.context.getUserId();
   var UserName = formContext.context.getUserName();
}

12. Get current record ID:

This function will get Current record GUID.

function CurrentRecID(context) {
   var formContext = context.getFormContext();
   var GUIDvalue = formContext.data.entity.getId();
}

13. Get User Security role:

This function will logged in user role.

function CurrentUserRolename(context) {
   var roleName = [ ];
   var formContext = context.getFormContext();
   var RoleIdArray = formContext.context.getUserRoles();
   
   for (i = 0; i < RoleIdArray.length; i++){
   
	var req = new XMLHttpRequest();
		req.open("GET", formContext.context.getClientUrl() + "/api/data/v9.1/roles("+RoleIdArray[i]+")?$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);
				var name = result["name"];
				roleName.push(name);
			} 
			else 
			{
				alert(this.statusText);
			}
		}
	};
	req.send();
}

alert(roleName);
   
}

14. Set field requirement:

This function will set the field as optional,required and recommended on form.

function SetRequirementLevel(context) {
   var formContext = context.getFormContext();
   //none = optional; required = Business required; recommended = Business recommended
   var AddressType = formContext.data.entity.attributes.get("telephone1").setRequiredLevel("required");
} 

15. Show/Hide Field:

This function will Hide/Show the field from the form.

function HideShowField(context) {
   var formContext = context.getFormContext();
   formContext.ui.controls.get("name").setVisible(false);
   //setVisible(false) to Hide; setVisible(True) to Show
}

16. Show/Hide Section:

This function will Hide/Show the section from tab in form.

function HideShowSection(context) {
   var formContext = context.getFormContext();
formContext.ui.tabs.get("SUMMARY_TAB").sections.get("Summary_section_6").setVisible(false);
   //setVisible(false) to Hide; setVisible(True) to Show
}

17. Show/Hide Tab:

This function will Hide/Show the section from form.

function HideShowTab(context) {
   var formContext = context.getFormContext();
   formContext.ui.tabs.get("SUMMARY_TAB").setVisible(false);
   //setVisible(false) to Hide; setVisible(True) to Show
}

18. Save form:

This function will save the form.

function Save(context) {
   var formContext = context.getFormContext();
   formContext.getAttribute("new_date").setValue(new Date());
   formContext.data.entity.save();
}

19. Save and Close form:

This function will save and close the form.

function SaveAndClose(context) {
   var formContext = context.getFormContext();
   formContext.getAttribute("new_date").setValue(new Date());
   formContext.data.entity.save("saveandclose");
}

20. Prevent Save:

This function will prevent user from saving the record. Best suited on save events.

function PreventSaveonSave(context) {
  var formContext = context.getEventArgs();
  if (formContext.getAttribute("websiteurl").getValue() == null) {
    alert("Add Wibsite Details");
    formContext.preventDefault();
  }
}

21. Get dirty fields:

Dirty fields are those fields which are not save in the data base yet.

function getDirty(context) {
   var formContext = context.getFormContext();
   formContext.getAttribute("new_date").setValue(new Date());//Dirty Field created 
   var attributes = formContext.data.entity.attributes.get()
    for (var i in attributes)
    {
       var attribute = attributes[i];
       if (attribute.getIsDirty())
       {
         alert("Dirty Fields: " + attribute.getName());
       }
    }
}

22. Get CRM URL:

This function will get CRM URL

function getURL(context) {
   var formContext = context.getFormContext();
   var URL = formContext.context.getClientUrl();
}

23. Set lookup window view:

This function will change the lookup view. For this we have used case entity and have changed default account entity to contact entity as well as the view to inactive contacts.

Get view Id from the URL.

function ChangeLookup(context) {
   var formContext = context.getFormContext();
   var control = formContext .getControl("customerid");
   control.getAttribute().setLookupTypes(["contact"]);
   var ViewGUID= "00000000-0000-0000-00AA-000010001033";
   formContext.getControl("customerid").setDefaultView(ViewGUID);
}

24. Change form view:

This function will change the form view.

function FormChange() {
    ChangeForm("Account for interactive experience");
}

function ChangeForm(formName) {

    var currentForm = Xrm.Page.ui.formSelector.getCurrentItem();
    var availableForms = Xrm.Page.ui.formSelector.items.get();

    if (currentForm.getLabel().toLowerCase() != formName.toLowerCase()) {
        for (var i in availableForms) {
            var form = availableForms[i];
            // try to find a form based on the name

            if (form.getLabel().toLowerCase() == formName.toLowerCase()) {
                form.navigate();
                return true;
            }
        }
    }
}

25. Pop up quick create form:

This function will pop up a quick create form.

function quickCreateCase(context){
   var formContext = context.getFormContext();
   var accountid = formContext.data.entity.getId();
   var accountName = formContext.getAttribute("name").getValue();
   var parentAccount = { entityType: "account", id: accountid, name: accountName };

   var parameters = {};
   parameters.title  = accountName;
   parameters.customerid = accountid;
   parameters.customeridname = accountName;
   parameters.customeridtype = "account";

   Xrm.Utility.openQuickCreate("incident", parentAccount, parameters);
}

26. Pop up entity blank form:

This function will open a blank form.

function BlankFormCase(context) {
    Xrm.Utility.openEntityForm("incident", null, null);
}

27. Pop up entity form with data:

This function will open an entity form with data.

function FormCreateCase(context){
   var formContext = context.getFormContext();
   var accountid = formContext.data.entity.getId();
   var accountName = formContext.getAttribute("name").getValue();
   var parentAccount = { entityType: "account", id: accountid, name: accountName };

   var parameters = {};
   parameters.title  = accountName;
   parameters.customerid = accountid;
   parameters.customeridname = accountName;
   parameters.customeridtype = "account";

   Xrm.Utility.openEntityForm("incident", null, parameters);
}

28. Pop up existing record:

This function will open an existing record.

function PopRec(context) {
    var formContext = context.getFormContext();
    var primaryContactGUID = formContext.getAttribute("primarycontactid").getValue()[0].id;
    if (primaryContactGUID != null) {
        Xrm.Utility.openEntityForm("contact", primaryContactGUID)
    }
}

29. Confirm/Cancel dialog:

This will pop up a confirmation dialog box.

function confirmBoxPopUp(context) {
   var confirmStrings = { text: "https://mscrmwithramandeep.home.blog/", title: "CRM is Awesome" };
   var confirmOptions = { height: 200, width: 450 };
   Xrm.Navigation.openConfirmDialog(confirmStrings, confirmOptions).then(
   function (success) {
       if (success.confirmed) {
           console.log("Dialog closed using OK button.");
       }
       else {
           console.log("Dialog closed using Cancel button or X.");
       }
   });
}

30. Pop up web resource:

This function will pop up web resources that could be image, JS, html page etc.

function PopWebResource() {
   Xrm.Utility.openWebResource("new_BlogJS");
   //new_BlogJS is the file name which was created in web resources
}

31. Retrieve data using CRM REST APIs:

This function will get the data of the entity as well as from the related entity. With OData query we can get data up to 2 levels. There is a very useful tool “CRM Rest Builder” from which you can generate ready to to use code.

function getDataRest(context){
   var formContext = context.getFormContext();
   var accountid ;
   accountid = formContext.data.entity.getId();
   accountid = accountid.replace("{", "");
   accountid = accountid.replace("}", "");
   var req = new XMLHttpRequest();
   req.open("GET", formContext.context.getClientUrl() + "/api/data/v9.1/accounts("+accountid+")?$select=accountnumber,name&$expand=primarycontactid($select=address1_telephone1,fullname)", 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);
               var accountnumber = result["accountnumber"];
               var name = result["name"];
               if (result.hasOwnProperty("primarycontactid")) {
                   var primarycontactid_address1_telephone1 = result["primarycontactid"]["address1_telephone1"];
                   var primarycontactid_fullname = result["primarycontactid"]["fullname"];
               }
           } else {
               Xrm.Utility.alertDialog(this.statusText);
           }
       }
   };
   req.send();
}

32. Retrieve data using fetch XML:

This function will get data using fetch XML. Fetch XML can be build and downloaded from advance find. Advantage with fetch XML is that with little changes in XML we can get data from multiple entity through multiple level.

function FetchRecords() {
    var FetchXMLQuery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>"+
   "  <entity name='account'>"+
   "    <attribute name='name' />"+
   "    <attribute name='accountid' />"+
   "    <order attribute='name' descending='false' />"+
   "    <filter type='and'>"+
   "      <condition attribute='accountid' operator='eq' value='7E04703C-63CD-E911-A812-000D3A0A82A5' />"+
   "    </filter>"+
   "    <link-entity name='contact' from='contactid' to='primarycontactid' visible='false' link-type='outer' alias='contact'>"+
   "      <attribute name='fullname' />"+
   "	  <link-entity name='systemuser' from='systemuserid' to='owninguser' visible='false' link-type='outer' alias='ContactOwner'>"+
   "      <attribute name='domainname' />"+
   "    </link-entity>"+
   "    </link-entity>"+
   "  </entity>"+
   "</fetch>";
 
    FetchXMLQuery = "?fetchXml=" + encodeURIComponent(FetchXMLQuery);
 
    
    Xrm.WebApi.retrieveMultipleRecords("account", FetchXMLQuery).then(
    function success(result) {
       if (result.entities.length != 0) {
		   var name = result.entities[0].name;
		   var contactFullname = result.entities[0]["contact.fullname"];
		   var domainname = result.entities[0]["ContactOwner.domainname"];
       } 
    },
    function (error) {
        
        
    });
}

I hope these function will help you with your requirements. Comment or get connected, if you have any query regarding JavaScript in MS Dynamics 365 CE. Will be happy to help.

Leave a comment

Design a site like this with WordPress.com
Get started