Thursday, August 28, 2014

Saving a CRM form with missing required fields

I ran across an interesting problem in that I needed to allow a CRM user to save the progress of a form that has required fields.  The required fields are not truly required until the user initiates a separate submission step.  I was able to "temporarily" remove the required from the fields and then put it back on after the save using this script:


function onSave() {
    var i = 0;
    Xrm.Page.ui.controls.forEach(function (control, index) {
        if (typeof control.getAttribute == 'function' && typeof control.getAttribute().getRequiredLevel == 'function' && control.getAttribute().getRequiredLevel() == "required") {
            reqControls[i] = control;
            control.getAttribute().setRequiredLevel("none");
            i++;
        }
    });
    Xrm.Page.data.save().then(onSaveComplete, onSaveFailed);
    
}

function onSaveComplete() {
    reqControls.forEach(function (control) {
        control.getAttribute().setRequiredLevel("required");
    });  
}