user329847
user329847

Reputation: 65

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.

Upvotes: 3

Views: 1102

Answers (2)

AdamV
AdamV

Reputation: 1467

Why let the user save the record at all?

You could use a Business Ruel to validate the field, and set an error condition against the field for values you don't "like". The error condition will persist and prevent them saving the record until they change the value. The error message can give them some explanation as to why their value is not valid.

Obviously the validation you can do in a Business Rule is limited, but your example does not make it clear on what basis we match "xyz" as a "bad" value.

Upvotes: 0

Henk van Boeijen
Henk van Boeijen

Reputation: 7918

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.

Upvotes: 2

Related Questions