executionContext.getEventArgs().preventDefault()无法阻止BPF阶段切换
解决Model Driven App中BPF阶段切换preventDefault()不生效问题
问题根源
你的代码存在两个关键问题导致preventDefault()无法阻止BPF阶段跳转:
- 异步时机错误:混用
await和then回调,preventDefault()在回调中执行时,PreStageChange事件已经完成阶段切换逻辑,错过了阻止时机。 - 条件判断错误:
if (activeStage = 'Configuration')是赋值操作而非等值判断,会导致逻辑意外触发。
修正后的代码
formContext.data.process.addOnPreStageChange(Sdk.validateApprovers); this.validateApprovers = async function (executionContext) { const formContext = executionContext.getFormContext(); const activeStage = formContext.data.process.getActiveStage().getName(); const terminationId = formContext.data.entity.getId().replace(/[{}]/g, ''); const args = executionContext.getEventArgs(); formContext.ui.clearFormNotification("ApproverError"); formContext.ui.clearFormNotification("RecipientError"); // 修正条件判断为等值比较 if (activeStage === 'Configuration') { const recipientOptions = `?$select=new_recipientid&$filter=statecode eq 0 and _new_relatedrecord_value eq ${terminationId}`; try { // 用await替代then回调,确保逻辑在主流程执行 const result = await Xrm.WebApi.retrieveMultipleRecords("new_recipient", recipientOptions); if (result.entities.length === 0) { const alertStrings = { confirmButtonLabel: "OK", text: "Recipients are not defined. Please specify.", title: "Warning" }; // 立即调用preventDefault(),不要放在异步回调里 args.preventDefault(); await Xrm.Navigation.openAlertDialog(alertStrings); } } catch (error) { console.log(error.message); } } }
关键改动说明
- 替换then回调为await:将异步请求处理放在async函数主流程中,确保
preventDefault()在事件处理周期内执行,不会错过阻止阶段切换的时机。 - 修正条件判断:把
=改为===,避免错误赋值导致逻辑异常。 - 提前获取EventArgs:提前缓存事件参数,确保能正确调用
preventDefault()。 - 使用try/catch处理异步错误:替代原错误回调,符合async/await语法规范。
内容的提问来源于stack exchange,提问作者PickyTech
相关产品推荐
相关产品推荐

