CRM 2011: JavaScript – An Assortment of JavaScript Code Snippets

When we are working with JavaScript in a CRM form, we must first work out which section of the form we want to reference.

Once that has been decided we have a variety of commands we can use.

I have already covered how to obtain a value from a lookup field and how to get the FormType in earlier posts so I will not repeat them here.

Below is some Javascript code snippets I frequently use on a day-to-day basis which i thought i would share here.

Note: All references to “fieldName”, “tabName” and “sectionName” refer to the Schema Names of the Field/Tab/Section and not their Display Names.

Getting a field value

Xrm.Page.getAttribute("fieldName").getValue();

Setting a field value

Xrm.Page.getAttribute("fieldName").setValue(value);

Clearing a field value

Xrm.Page.getAttribute("fieldName").setValue(null);

Getting a picklist’s option text

//Note: The previous get/set commands will also work fine with picklists
//Although when setting a value, we set the numeric value not the text value
Xrm.Page.getAttribute("fieldName").getSelectedOption().text;

Setting the requirement level of a field

Xrm.Page.getAttribute("fieldName").setRequiredLevel("none");
Xrm.Page.getAttribute("fieldName").setRequiredLevel("recommended");
Xrm.Page.getAttribute("fieldName").setRequiredLevel("required");

Enable/Disable a field

Xrm.Page.ui.controls.get("fieldName").setDisabled(false); //Enabled
Xrm.Page.ui.controls.get("fieldName").setDisabled(true); //Disabled

Setting a field’s visibility

Xrm.Page.ui.controls.get("fieldName").setVisible(true); //visible
Xrm.Page.ui.controls.get("fieldName").setVisible(false); //not visible

Setting a tab’s visibility

Xrm.Page.ui.tabs.get("tabname").setVisible(true); //visible
Xrm.Page.ui.tabs.get("tabname").setVisible(false); //not visible

Xrm.Page.ui.tabs.get("tabName").setVisible(true); //visible
Xrm.Page.ui.tabs.get("tabName").setVisible(false); //not visible

Setting a section’s visibility

//visible
Xrm.Page.ui.tabs.get("tabName").sections.get("sectionName").setVisible(true);

//not visible
Xrm.Page.ui.tabs.get("tabName").sections.get("sectionName").setVisible(false); 

Get the Guid of the current record

Xrm.Page.data.entity.getId();