When writing custom JavaScript code for Dynamics, many of the same code lines are often used when adding functionality to forms, fields, or ribbon buttons. In this post, I’ve collected some short code snippets that I often use. The examples are meant to be a look-up guide or a cheat sheet to have a place to get the snippet needed quickly.
In the screenshots in this post, there are used
methods instead of the Xrm.Page
on some examples. The reason behind this is that you don’t need to add a function to a form to see what the code does. The formContext
is deprecated but I find it useful to find values and to see what the code does before I add it to a form.Xrm.Page
Below you will find different snippets and screenshots of the result in the developer console. This is no complete cheat sheet list, but some of the snippets that came to mind at the time of writing.
How to Get the Current Row id and Replace the Brackets With JavaScript
let contactId = formContext.data.entity.getId().replace(/{|}/g, '');
How to return the form that is currently displaying
Return the form that is currently displaying.
formContext.ui.formSelector.getCurrentItem();
Example result from the snippet:
How to Get the Entity Reference of the Current Row With JavaScript
Return the look-up value of the current record. Another way to retrieve the current record id.
formContext.data.entity.getEntityReference();
How to Get a Parent Account Related to a Contact with JavaScript
let contactId = formContext.data.entity.getId().replace(/{|}/g, ''); let result = await Xrm.WebApi.retrieveRecord("contact", contactId, "?$select=firstname,lastname,contactid&$expand=parentcustomerid_account($select=accountid,name)"); let parentAccount = result['parentcustomerid_account']; let accountId = result['parentcustomerid_account'].accountid; let accountName = result['parentcustomerid_account'].name; console.log("contactId: ", contactId); console.log("result: ", result); console.log("parentAccount: ",parentAccount); console.log("accountId : ",accountId); console.log("accountName : ", accountName);
How to Get the Primary Contact for an Account with JavaScript
let accountId = formContext.data.entity.getId().replace(/{|}/g, ''); let result = await Xrm.WebApi.retrieveRecord("account", accountId, "?$select=name&$expand=primarycontactid($select=contactid,fullname)") let primaryContact = result['primarycontactid']; let contactId = result['primarycontactid'].contactid; let contactName = result['primarycontactid'].fullname; console.log("primaryContact: ",primaryContact); console.log("contactId: ",contactId); console.log("contactName: ", contactName);
How to Get Values From a Look-up field with JavaScript
let primaryContact = formContext.getAttribute("primarycontactid").getValue(); let primaryContactId = primaryContact[0].id.replace(/{|}/g, ""); let primaryContacName = primaryContact[0].name; console.log("primaryContact: ", primaryContact); console.log("primaryContactId: ", primaryContactId); console.log("primaryContacName: ", primaryContacName);
How to Get Form Type With JavaScript
let formType = formContext.ui.getFormType(); // 0 Undefined // 1 Create // 2 Update // 3 Read Only // 4 Disabled // 6 Bulk Edit // Quick Create forms return 1
How to Show and Hide a Field on a Form with JavaScript
//Show formContext.getControl("FieldName").setVisible(true); //Hide formContext.getControl("FieldName").setVisible(false);
How to Show and Hide Sections on a Form with JavaScript
// Hide section within a specified tab let tab = formContext.ui.tabs.get("TabName"); let section = tab.sections.get("SectionName"); section.setVisible(false); // Show section within a specified tab let tab = formContext.ui.tabs.get("TabName"); let section = tab.sections.get("SectionName"); section.setVisible(true);
How to Set Required Fields in Dynamics 365 with JavaScript
Sets a field to required, recommended, or none.
formContext.getAttribute("fieldname").setRequiredLevel("required"); formContext.getAttribute("fieldname").setRequiredLevel("recommended"); formContext.getAttribute("fieldname").setRequiredLevel("none");
How to Set Tab in Focus with JavaScript
Sets the desired tab in focus.
let defaultTab = formContext.ui.navigation("tab").getId(); formContext.ui.navigation.setFocus();
How to Set Value in a Look-up Field with JavaScript
let lookupValue = new Array(); lookupValue[0] = new Object(); lookupValue[0].id = "465b158c-541c-e511-80d3-3863bb347ba8"; lookupValue[0].entityType = "contact"; formContext.getAttribute("primarycontactid").setValue(lookupValue);
How to Get Current App URL with JavaScript
let globalContext = Xrm.Utility.getGlobalContext(); globalContext.getCurrentAppUrl();
Retrieves the following:
How to Get Current AppId and app Display Name with JavaScript
let globalContext = Xrm.Utility.getGlobalContext(); let appProperties = await globalContext.getCurrentAppProperties(); let appId = appProperties.appId; let displayName = appProperties.displayName; let uniqueName = appProperties.uniqueName; // Output console.log("appId: ", appId); console.log("displayName: ", displayName); console.log("uniqueName: ", uniqueName);
Retrieves the following:
How to Get The Current User id With JavaScript
let userSettings = Xrm.Utility.getGlobalContext().userSettings; let userId = userSettings.userId;
Retrieves the following:
How to Get Security Roles of the Current User With JavaScript
let userSettings = Xrm.Utility.getGlobalContext().userSettings let securityRoles = userSettings.securityRoles;
Retrieves the following:
How to Get the User Settings of the Current User
let userSettings = Xrm.Utility.getGlobalContext().userSettings;
Retrieves the following:
How to Retrieve Values From Environment Variables with JavaScript
The function below gets the value specified in an environment variable by passing the Schema Name of the variable and gets the specified value and not the standard value.
This function lets you retrieve JSON-object:
// Function for retrieving environment variables async function _getEnvironmentVariable(variableSchemaName) { try { const retrieveVariableResult = await Xrm.WebApi.retrieveMultipleRecords("environmentvariabledefinition", `?$filter=schemaname eq '${variableSchemaName}'&$expand=environmentvariabledefinition_environmentvariablevalue($select=value)&$top=1`).then( function success(result) { for (let i = 0; i < result.entities.length; i++) { let variableValue = result.entities[i].environmentvariabledefinition_environmentvariablevalue; if (typeof (variableValue) !== undefined && variableValue.length > 0) { let parseVariableValue = JSON.parse(variableValue[0].value); return parseVariableValue; } else { throw new Error(`The value for the variable ${variableSchemaName} is empty`); } } }, function (error) { return error.message; } ); return retrieveVariableResult; } catch (error) { return error.message; } }
This function lets you retrieve a single text value from an environment variable:
this._getEnvironmentVariable = async function (variableSchemaName) { try { const retrieveVariableResult = await Xrm.WebApi.retrieveMultipleRecords("environmentvariabledefinition", `?$filter=schemaname eq '${variableSchemaName}'&$expand=environmentvariabledefinition_environmentvariablevalue($select=value)&$top=1`).then( function success(result) { for (let i = 0; i < result.entities.length; i++) { let variableValue = result.entities[i].environmentvariabledefinition_environmentvariablevalue; if (typeof (variableValue) !== undefined && variableValue.length > 0) { return variableValue[0].value; } else { throw new Error(`The value for the variable ${variableSchemaName} is empty`); } } }, function (error) { return error.message; } ); return retrieveVariableResult; } catch (error) { return error.message; } }
Updated function for retrieving JSON and text variables:
// Function for retrieving environment variables async function _getEnvironmentVariable(variableSchemaName, datatype) { try { const result = await Xrm.WebApi.retrieveMultipleRecords( "environmentvariabledefinition", `?$filter=schemaname eq '${variableSchemaName}'&$expand=environmentvariabledefinition_environmentvariablevalue($select=value)&$top=1` ); for (let i = 0; i < result.entities.length; i++) { let variableValue = result.entities[i].environmentvariabledefinition_environmentvariablevalue; if (variableValue && variableValue.length > 0) { if (datatype === 'json') { try { return JSON.parse(variableValue[0].value); // Returns the parsed JSON object } catch (e) { throw new Error(`Value for ${variableSchemaName} is not valid JSON.`); } } else if (datatype === 'text') { return variableValue[0].value; // Returns the value as text } else { throw new Error(`Invalid datatype parameter. Must be 'json' or 'text'.`); } } else { throw new Error(`The value for the variable ${variableSchemaName} is empty`); } } throw new Error(`No entities found for variable ${variableSchemaName}`); } catch (error) { throw error; // Or handle the error as needed } }