Search code examples
javascriptdynamics-crmdynamics-365powerapps-modeldriven

Autosaving a form when an input field gets dirty in Dynamics 365


What's wrong with this script? I'm getting this error - Script Error - One of the scripts for this record has caused an error. For more details, download the log file.

function autosaveWhenFieldIsDirty(formContext)
{
    var isFieldDirty = formContext.getAttribute("logdate").getIsDirty();

    var saveOptions = {
        saveMode: 70
    };

    if(isFieldDirty == true)
    {
        formContext.data.save(saveOptions).then(
            function (success) {
                console.log(success);
            },
            function (error) {
                console.log(error);
            }
        );
    }
}

Solution

  • I believe the main issue with your script is related to the parameter. When the function is bound to onchange event executionContext is passed in the handler and not formContext so you should try the following code instead:

    function autosaveWhenFieldIsDirty(executionContext) {
    var formContext = executionContext.getFormContext();
    
    var isFieldDirty = formContext.getAttribute("logdate").getIsDirty();
    
    var saveOptions = {
        saveMode: 70
    };
    
    if (isFieldDirty == true) {
        formContext.data.save(saveOptions).then(
            function(success) {
                console.log(success);
            },
            function(error) {
                console.log(error);
            }
        );
    }
    

    }