发生异常时撤消表单更改

Undo form changes when an exception occurs

在 Dynamics CRM 2013 中,是否可以在发生业务流程错误时还原表单上更改的字段?

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

我们想要的行为是 'xyz' 在步骤 5 中恢复到 'abc'。

您需要先缓存数据。你可以这样做 OnLoad,例如通过记住实体的属性值:

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();

然后需要通过Xrm.Page.data.save方法进行保存操作。传递处理错误和重置字段的回调函数,例如

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()]);
         }
      });
   });

无法使用 save 事件以这种方式重置表单的字段,因为它在实际保存操作之前启动,永远不会在它之后启动。

为什么要让用户保存记录呢?

您可以使用 Business Ruel 来验证该字段,并针对您不想要的值设置错误条件 "like"。错误条件将持续存在并阻止他们保存记录,直到他们更改值。错误消息可以向他们解释为什么他们的值无效。

显然,您可以在业务规则中进行的验证是有限的,但是您的示例没有说明我们将 "xyz" 匹配为 "bad" 值的依据。