Search code examples
dynamics-crmdynamics-crm-2015

How to disable a Dynamics CRM field when the value changes without breaking save?


We have a two state field called Primary that is set to either yes or no. When the field is set to no, the user should be able to change it to yes. When the field is set to yes, it should be disabled, so the user can no longer change it.

We have code in the onload event that handles this; that works just fine. The challenging case is the one where a user changes the field from no to yes and then saves the form. This should lock the field so the user can't change it back to no. We attempted to solve this by putting the following code in onsave event:

export function onSave() {
    var primaryControl = Xrm.Page.getControl(
            d.ConstituentAffiliation.AttributeNames.Primary.toLowerCase());
        if (primaryControl) {
            if (primaryControl.getAttribute().getValue()) {
                primaryControl.setDisabled(true);
            }
            else {
                primaryControl.setDisabled(false);
            }
        }
    }

This partly works. It does disable the field so it can no longer be changed. The save doesn't work, however, because Dynamics CRM appears not to send the values of disabled fields back to the server during the save, so the new value does not actually get saved.

Any ideas would be welcome. :)


Solution

  • It seems the following line solves my problem:

    Xrm.Page.getAttribute(d.ConstituentAffiliation.AttributeNames.Primary
        .toLowerCase()).setSubmitMode("always");
    

    So the code now reads as follows:

    export function onSave() {
    
        var primaryControl = Xrm.Page.getControl( d.ConstituentAffiliation.AttributeNames.Primary.toLowerCase());
    
        if (primaryControl) {
            if (primaryControl.getAttribute().getValue()) {
                Xrm.Page.getAttribute( d.ConstituentAffiliation.AttributeNames.Primary.toLowerCase() ).setSubmitMode("always");
                primaryControl.setDisabled(true);
            }
            else {
                primaryControl.setDisabled(false);
            }
        }
    }   
    

    I should credit this blog which was very helpful: http://blogs.msdn.com/b/arpita/archive/2012/02/19/microsoft-dynamics-crm-2011-force-submit-on-a-disabled-field-or-read-only-field.aspx