Bhubaneswar, Odisha, India
+91-8328865778
support@softchief.com

20 Most Commonly Used JavaScript Scenarios with Sample Code Snippets in Form Script – Dataverse / Dynamics 365 CE

20 Most Commonly Used JavaScript Scenarios with Sample Code Snippets in Form Script – Dataverse / Dynamics 365 CE

JavaScript plays a critical role in Microsoft Dataverse and Dynamics 365 Customer Engagement (CE) applications. While Power Automate and Business Rules help automate processes, JavaScript remains essential for realtime client-side customization and enhanced user experience.

Using JavaScript in Model-Driven Apps allows developers to:

  • Validate data instantly
  • Auto-populate fields
  • Control form behavior dynamically
  • Improve user experience
  • Trigger business logic
  • Integrate with Dataverse Web API
  • Customize ribbon and command actions

In this blog, we’ll explore 20 of the most commonly used JavaScript scenarios in Dynamics 365 CE / Dataverse with practical sample snippets used in real-world enterprise implementations.


1. Show Alert on Form Load

Business Scenario

Display a welcome message or important information when the form opens.

Event

  • Form OnLoad

JavaScript Snippet

function formOnLoad(executionContext) {
var formContext = executionContext.getFormContext();
  Xrm.Navigation.openAlertDialog({text: "Welcome to Dynamics 365 CE"});
  }

2. Auto Populate Full Name

Business Scenario

Automatically combine First Name and Last Name into Full Name.

Event

  • OnChange

JavaScript Snippet

function setFullName(executionContext) {
    var formContext = executionContext.getFormContext();
        var firstName = formContext.getAttribute("firstname").getValue();
        var lastName = formContext.getAttribute("lastname").getValue();
            if (firstName && lastName) {
              formContext.getAttribute("fullname").setValue(firstName + " " + lastName);
    }
}

3. Make Field Mandatory Dynamically

Business Scenario

If customer type is VIP, PAN Number becomes mandatory.

JavaScript Snippet

function setMandatoryField(executionContext) {
    var formContext = executionContext.getFormContext();
       var customerType = formContext.getAttribute("new_customertype").getValue();
           if (customerType === 100000001) {
                   formContext.getAttribute("new_pannumber")           .setRequiredLevel("required");   
                   } else {        
                   formContext.getAttribute("new_pannumber")            .setRequiredLevel("none");
   }
}

4. Hide and Show Fields Dynamically

Business Scenario

Show GST Number only for Business Customers.

JavaScript Snippet

function toggleGSTField(executionContext) {
var formContext = executionContext.getFormContext();

var type = formContext.getAttribute("customertypecode").getValue();

if (type === 1) {
formContext.getControl("new_gstnumber").setVisible(true);
} else {
formContext.getControl("new_gstnumber").setVisible(false);
}
}

5. Disable Field Based on Status

Business Scenario

Lock fields when record becomes Approved.

JavaScript Snippet

function disableFields(executionContext) {
var formContext = executionContext.getFormContext();

var status = formContext.getAttribute("statuscode").getValue();

if (status === 100000001) {
formContext.getControl("new_amount").setDisabled(true);
}
}

6. Prevent Save Based on Validation

Business Scenario

Prevent saving if Age is below 18.

JavaScript Snippet

function validateAge(executionContext) {
var formContext = executionContext.getFormContext();
var eventArgs = executionContext.getEventArgs();

var age = formContext.getAttribute("new_age").getValue();

if (age < 18) {
Xrm.Navigation.openAlertDialog({
text: "Age must be 18 or above."
});

eventArgs.preventDefault();
}
}

7. Set Field Notification

Business Scenario

Warn user about missing information.

JavaScript Snippet

function showNotification(executionContext) {
var formContext = executionContext.getFormContext();

formContext.getControl("telephone1")
.setNotification("Phone number is recommended.");
}

8. Clear Notification

JavaScript Snippet

function clearNotification(executionContext) {
var formContext = executionContext.getFormContext();

formContext.getControl("telephone1")
.clearNotification();
}

9. Auto Set Current Date

Business Scenario

Automatically populate today’s date.

JavaScript Snippet

function setTodayDate(executionContext) {
var formContext = executionContext.getFormContext();

formContext.getAttribute("new_followupdate")
.setValue(new Date());
}

10. Get Logged-In User Details

Business Scenario

Retrieve current logged-in user information.

JavaScript Snippet

function getCurrentUser() {

var userName = Xrm.Utility.getGlobalContext()
.userSettings.userName;

var userId = Xrm.Utility.getGlobalContext()
.userSettings.userId;

console.log(userName);
console.log(userId);
}

11. Open Custom Dialog

Business Scenario

Open custom pages or dialogs from form.

JavaScript Snippet

function openDialog() {

var pageInput = {
pageType: "webresource",
webresourceName: "new_customdialog.html"
};

var navigationOptions = {
target: 2,
width: 500,
height: 400,
position: 1
};

Xrm.Navigation.navigateTo(pageInput, navigationOptions);
}

12. Call Dataverse Web API

Business Scenario

Retrieve account details dynamically.

JavaScript Snippet

function retrieveAccount() {

Xrm.WebApi.retrieveRecord("account",
"GUID-HERE",
"?$select=name,revenue")
.then(function success(result) {

console.log(result.name);

}, function (error) {

console.log(error.message);
});
}

13. Create Record Using JavaScript

Business Scenario

Create follow-up task automatically.

JavaScript Snippet

function createTask() {

var entity = {};

entity.subject = "Follow up with customer";

Xrm.WebApi.createRecord("task", entity)
.then(function success(result) {

console.log(result.id);

}, function (error) {

console.log(error.message);
});
}

14. Update Existing Record

Business Scenario

Update customer category dynamically.

JavaScript Snippet

function updateAccount(accountId) {

var entity = {};
entity.name = "Updated Account";

Xrm.WebApi.updateRecord("account", accountId, entity)
.then(function success() {

console.log("Updated");

}, function (error) {

console.log(error.message);
});
}

15. Delete Record

Business Scenario

Delete temporary records automatically.

JavaScript Snippet

function deleteRecord(recordId) {

Xrm.WebApi.deleteRecord("account", recordId)
.then(function success() {

console.log("Deleted");

}, function (error) {

console.log(error.message);
});
}

16. Filter Lookup Dynamically

Business Scenario

Show only active contacts in lookup.

JavaScript Snippet

function filterLookup(executionContext) {

var formContext = executionContext.getFormContext();

formContext.getControl("primarycontactid")
.addPreSearch(function () {

var filter =
"<filter type='and'>" +
"<condition attribute='statecode' operator='eq' value='0' />" +
"</filter>";

formContext.getControl("primarycontactid")
.addCustomFilter(filter, "contact");
});
}

17. Refresh Form Automatically

Business Scenario

Refresh form after custom operation.

JavaScript Snippet

function refreshForm(executionContext) {

var formContext = executionContext.getFormContext();

formContext.data.refresh(true);
}

18. Open Record Using JavaScript

Business Scenario

Navigate to related account record.

JavaScript Snippet

function openAccount(accountId) {

var entityFormOptions = {};

entityFormOptions.entityName = "account";
entityFormOptions.entityId = accountId;

Xrm.Navigation.openForm(entityFormOptions);
}

19. Add Form Level Notification

Business Scenario

Show warning message across form.

JavaScript Snippet

function showFormNotification(executionContext) {

var formContext = executionContext.getFormContext();

formContext.ui.setFormNotification(
"Customer credit limit exceeded.",
"WARNING",
"creditwarning"
);
}

20. Remove Form Notification

JavaScript Snippet

function clearFormNotification(executionContext) {

var formContext = executionContext.getFormContext();

formContext.ui.clearFormNotification("creditwarning");
}

JavaScript Best Practices in Dynamics 365 CE

1. Always Use executionContext

var formContext = executionContext.getFormContext();

Avoid using deprecated Xrm.Page.


2. Avoid Hardcoding GUIDs

Store configurations in:

  • Environment Variables
  • Custom Configuration Tables
  • Secure Settings

3. Use Namespaces

Avoid global functions.

var Softchief = Softchief || {};

4. Minimize API Calls

Retrieve only required columns.

?$select=name

5. Use Async Operations

Avoid blocking UI.


Common Enterprise JavaScript Use Cases

IndustryCommon JavaScript Usage
BankingValidation, KYC checks
HealthcareAppointment validation
RetailInventory checks
InsurancePolicy verification
EducationStudent eligibility
LogisticsShipment tracking
TelecomService activation
ManufacturingWorkflow automation

Recommended Event Registrations

ScenarioEvent
Default ValuesOnLoad
ValidationOnSave
Field CalculationsOnChange
Lookup FilteringPreSearch
UI ChangesOnChange

Final Thoughts

JavaScript remains one of the most important customization tools in Microsoft Dataverse and Dynamics 365 CE.

Even with the rise of low-code development, JavaScript continues to provide:

  • Advanced UI customization
  • Dynamic validations
  • Rich client-side interactions
  • Web API integrations
  • Better user experiences

Mastering these common JavaScript scenarios is essential for every Power Platform and Dynamics 365 developer.

If you are preparing for enterprise projects, client implementations, or technical interviews, these are among the most frequently used JavaScript scenarios you should know.

Leave a Reply