Tips Model-Driven Apps Javascript: How to trigger Custom Method After Saving

Have you ever had a scenario that needs to disable all the controls in the UI after data is successfully saved? Let’s say after the document State changed to Approved, then we need to disable some of the attributes in the form? If yes, then this post is about my simple tips to achieve that scenario.

Do you know when CRM successfully saved data in the back-end, then it will push those attributes that are being changed (in the process) to the UI and if you register a JavaScript event on that attribute, it will trigger the changed event? For a simple demonstration, let’s make a JavaScript like this:

var Blog = Blog || {};
Blog.Form = Blog.Form || {};
(function () {
    this.modifiedOnChange = function(context) {
        console.log('hi from javascript');
    };
}).apply(Blog.Form);

For this demonstration, I register this JavaScript in attribute Modified On Changed events like this:

This is the result if we save the data:

After successfully saved CRM will trigger the method that we register in ModifiedOn attribute

With this logic, we can do that scenario (call formOnLoad method/other methods after successfully save) more elegantly. This is my sample of the code:

var Blog = Blog || {};
Blog.Form = Blog.Form || {};
(function () {
    var disabledAll = function(context) {
        var formContext = context.getFormContext();

        formContext.ui.controls.forEach(control => {
            if(control.setDisabled) {
                control.setDisabled(true);
            }
        });
    };

    this.formOnLoad = function (context) {
        var formContext = context.getFormContext();
        var name = formContext.getAttribute('new_name').getValue()
        if(name === 'Disabled') {
            disabledAll(context);
        }
    };

    this.modifiedOnChange = function(context) {
        Blog.Form.formOnLoad(context);
    };
}).apply(Blog.Form);

If the name of the record is “Disabled” then I will lock all the attributes on formOnLoad (you can change this logic with statecode/statuscode).

This is the demonstration for it:

Hope you enjoy it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.