[TIPS] Difference between formContext.data.entity.addOnLoad() and Add function to form on load event directly

 [TIPS] Difference between formContext.data.entity.addOnLoad() and Add function to form on load event directly

Let's say you have two options for adding functions to the form's onLoad event. 

  • Option 1 is to add functions A, B, and C to the onLoad() function that's registered for the form onload event using the form properties. 
  • Option 2 is to use formContext.data.entity.addOnLoad() to add functions A, B, and C. 

What is the difference between these two options?


In both options, you are adding functions A, B, and C to the form's onLoad event. The main difference is in how you are registering those functions to the onLoad event.

In option 1, you are registering the onLoad function to the form's onLoad event using the form properties. Inside the onLoad function, you are adding functions A, B, and C to the form's onLoad event.

In option 2, you are using the formContext.data.entity.addOnLoad() method to register functions A, B, and C directly to the form's onLoad event.

Both options achieve the same result, but option 2 provides more flexibility as you can dynamically register and unregister functions to the onLoad event at runtime. Option 1 is a more static approach, and it requires you to modify the form properties to make changes to the onLoad event.


For example:

There is a field named A in form B. Function C was registered as the handler for the field A onchange event. When field A's value changes to "E", function D will be triggered each time when the form on loaded from then on. Or else, function D will not be triggered when each form is loaded from then on.

function C(executionContext) {
  // Get the form context from the execution context
  const formContext = executionContext.getFormContext();

  // Get the "A" control from the form context
  const control = formContext.getControl("A");

  // Define the function D
  function D() {
    // Function D logic goes here
  }

  // Register function D for form onload event if the value is "E"
  control.addOnChange(() => {
    const value = control.getAttribute().getValue();
    if (value === "E") {
      formContext.data.entity.addOnLoad(D);
    } else {
      formContext.data.entity.removeOnLoad(D);
    }
  });
}

No comments:

Post a Comment