Search code examples
javascriptdynamics-crmdynamics-crm-2013

Undo form changes when an exception occurs


In Dynamics CRM 2013 is it possible to revert a field changed on a form when a business process error occurs?

For example:
1. User changes a text field on a form from 'abc' to 'xyz'
2. User clicks save
3. CRM pre-operation plugin validates field, 'xyz' not allowed, exception   thrown
4. CRM displays business process error to user, 'xyz' is not allowed
5. The value 'xyz' is still shown in the form

The desired behavior we want is 'xyz' to revert to 'abc' in step 5.


Solution

  • You will need to cache the data first. You can do this OnLoad, e.g. by memorizing the entity's attribute values:

    function GetInitialAttributeState() {
       var preImage = {};
    
       Xrm.Page.data.entity.attributes.forEach(function(field) {
          // TODO: for lookup attributes you need to do extra work in order to avoid making merely a copy of an object reference.
          preImage[field.getName()] = field.getValue();
       });
    
       return preImage;
    }
    
    window.preImage = GetInitialAttributeState();
    

    Then you need to perform the save operation through the Xrm.Page.data.save method. Pass a callback function handling errors and resetting the fields, e.g.

    Xrm.Page.data.save().then(
       function() {
          /* Handle success here. */
          window.preImage = getInitialAttributeState();
       },
       function() {
          /* Handle errors here. */
          Xrm.Page.data.entity.attributes.forEach(function(field) {
             if (field.getIsDirty()) {
                field.setValue(preImage[field.getName()]);
             }
          });
       });
    

    It is not possible to reset the form's fields this way using the save event, because it kicks in before the actual save operation, never after it.