FormLoaded event - Dynamics 365
In Dynamics 365, the Form OnLoad event is a common method for initiating code when a form loads. However, relying solely on this event has drawbacks, such as potential data inconsistency or slower performance, especially when making external API calls. For example, if you use OnLoad to fetch data from a third-party service and perform operations on it, the data might not be fully loaded when needed, leading to delays or errors.
To address these issues, Microsoft introduced the Form Loaded event, which occurs only after the form has completed loading. This event lets you delay non-essential logic, like API calls or field population, until the form is fully ready. By moving complex operations to the Form Loaded event, you can optimize loading times and enhance data reliability.
To use this event, you register code via formContext.ui.addLoaded and formContext.ui.removeLoaded. Here’s an example to illustrate:
function onFormLoad(executionContext) {
const formContext = executionContext.getFormContext();
// Adding a function to run after form load completes
formContext.ui.addLoaded(loadAdditionalData);
}
async function loadAdditionalData() {
console.log("Form loaded successfully.");
const formContext=Xrm.Page.data;
try {
// Sample call to an external service
const response = await fetch("https://apiexample.com/sample");
if (response.ok) {
const data = await response.json();
// Update the form field based on fetched data
formContext.entity.attributes.get("field1").setValue(data.field1);
console.log("Additional data loaded.");
} else {
console.error("Failed to fetch additional data.");
}
} catch (error) {
console.error("Error fetching data:", error);
}
}In this sample, the loadAdditionalData function runs only after the form is fully loaded, improving both performance and data consistency.
Comments
Post a Comment