Based on the experiences in various CRM projects, I would like to share some of the best practices which will be helpful to make JS files easy to maintain, reusable, reliable and with industry code standards.
1. Create JS files with namespace and add all functions, objects and properties to the namespace.
Example:
// Namespace in project level
var SCH = SCH || {};
// Namespace in js file level
SCH.RescheduleOrder = SCH.RescheduleOrder || {};
// Object declaration
SCH.RescheduleOrder.StateCodeValues = {
Active: 0,
Inactive: 1
};
// Function declaration
SCH.RescheduleOrder.onLoad = function (executionContext) {
"use strict";
var formContext = executionContext.getFormContext();
//Usage of object inside the function
if (formContext.getAttribute("statecode").getValue() === SCH.RescheduleOrder.StateCodeValues.Active) {
// To do;
}
};
2. "use strict" directive inside every function. This will help us to avoid the undeclared usage of variables and objects, restrict writing to read only property and get only property and so on.Example:
// Function declaration
SCH.RescheduleOrder.onLoad = function (executionContext) {
"use strict";
var formContext = executionContext.getFormContext();
//Usage of object inside the function
if (formContext.getAttribute("statecode").getValue() === SCH.RescheduleOrder.StateCodeValues.Active) {
// To do;
}
};
3. Keep generic functions like, retrieving the Configuration/settings record, common date comparisons, global options set values in a separate JS file and call wherever needed.
4. Create an object and declare entity names, attributes instead of hard coding directly in the code.
Example:
// Attributes
SCH.RescheduleOrder.Attributes = {
ExpiryDate: "new_expirydate",
RescheduleStatus: "new_reschedulestatus"
}
SCH.RescheduleOrder.onLoad = function (executionContext) {
"use strict";
var formContext = executionContext.getFormContext();
// Usage of the attributes in the function
var expiryDate = formContext.getAttribute(SCH.RescheduleOrder.Attributes.ExpiryDate).getValue();
};
5. Use Xrm.WebApi.online method to make CRM calls and use async and await for running in synchronously instead of using XMLHttpRequest.
Example:
async function GetConfigSettings(viewName) {
try {
var result = await Xrm.WebApi.online.retrieveMultipleRecords("new_configsetting", "?$select=new_value&$filter=new_name eq '" + viewName + "'").then(
function success(results) {
if (results.entities.length > 0) {
return results.entities[0]["new_value"];
}
},
function (error) {
return error.message;
}
);
return result;
}
catch (e) {
return e.message;
}
};
Comments
Post a Comment