我在 Dynamics CRM 中有一个 Web 资源,我正在尝试添加在保存时执行的逻辑。我正在使用 addOnSave()
方法将我的逻辑附加到保存中。当我在保存逻辑中使用 Promise 时,保存并关闭会在保存完成之前退出页面。如何在 Web 资源关闭之前完全执行我的保存逻辑?
伪代码
Xrm.Event.addOnSave(function () {
// Code makes it here
Promise.all([promises]).then(function(){
// Code never makes it here
secondPromise.then(function(){
showAlert();
setTimeout(function(){
closeAlert();
}, 5000);
});
});
});
最佳答案
您想要取消保存然后重新发出它,如下所示:
Xrm.Page.data.entity.addOnSave(function (context) {
var eventArgs = context.getEventArgs();
eventArgs.preventDefault(); // cancels the save (but other save handlers will still run)
Promise.all([promises]).then(function(){
// Code never makes it here
secondPromise.then(function(){
showAlert();
setTimeout(function(){
closeAlert();
// reissue the save
Xrm.Page.data.entity.save('saveandclose');
}, 5000);
});
});
});
为了回应您有关 PreventDefault 无法正确停止“保存并关闭”事件的错误的评论:使用 XrmToolbox 中的功能区工作台覆盖“保存并关闭”按钮以指向可能如下所示的自定义函数:
function customSaveAndClose() {
if (customSaveIsNeeded) {
// execute your custom code
} else {
Xrm.Page.data.entity.save('saveandclose');
}
}
您当然可以在应用程序功能区级别覆盖 S&C 按钮,这将为所有实体覆盖它,但我相信您也可以一次仅为一个实体覆盖它。
如果您不想编辑功能区(如果您以前从未这样做过,这有点令人生畏),并且如果您对不支持的自定义没有严格要求,您也可以采取更简单的方法只需重写 Mscrm.RibbonActions.saveAndCloseForm 函数,该函数是 native S&C 按钮所调用的函数。看起来像这样:
// defined in /_static/_common/scripts/RibbonActions.js
Mscrm.RibbonActions.saveAndCloseForm = function() {
// your code here
}
有关此方法的一些注意事项:
- 它不受支持,并且可能会因任何更新而中断
- CRM 表单由多个框架组成,因此,如果您在自定义脚本中定义该函数但该函数未执行,请将您的定义更改为
top.Mscrm
,而不仅仅是Mscrm
。 - 如果您必须支持移动客户端,则可能应该避免这种方法并覆盖功能区按钮。
关于javascript - 表单事件OnSave不执行Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45945024/