在 Dynamics CRM 开发中,我们一般要利用 JS 来做一些数据验证的功能,我们也需要将验证结果显示出来,比起直接 alert 出信息来提示用户的方式,CRM 提供了更加美观和人性化的方式来通知用户是否存在错误输入。
一、为字段设置 Notification:
代码如下:
var oStartDate = Xrm.Page.getAttribute("new_start_date").getValue(); var oEndDate = Xrm.Page.getAttribute("new_end_date").getValue(); var sMsg = null; if (oStartDate != null && oEndDate != null && oStartDate > oEndDate) { sMsg = "End Date must be later than or on the same day as Start Date."; Xrm.Page.getControl("new_end_date").setNotification(sMsg); } else { Xrm.Page.getControl("new_end_date").clearNotification(); }
效果如下:
Note:此时 CRM 系统不允许保存该记录,只有在输入正确的值,清除掉 Notification 信息之后才可以保存这条记录。
二、在 Form 上设置 Notification:
代码如下:
var id = "Note_Terminate_Date"; var sMsg = "Terminate Date must be later than or on the same day as First Join Date."; var firstJoinDate = Xrm.Page.getAttribute("new_first_join_date").getValue(); var terminateDate = Xrm.Page.getAttribute("new_terminate_date").getValue(); if (firstJoinDate != null && terminateDate != null && firstJoinDate > terminateDate) { Xrm.Page.ui.clearFormNotification(id); Xrm.Page.ui.setFormNotification(sMsg, "ERROR", id); Xrm.Page.getAttribute("new_terminate_date").setValue(null); } else if (firstJoinDate != null && terminateDate != null && firstJoinDate <= terminateDate) { Xrm.Page.ui.clearFormNotification(id); }
效果如下:
Note:这里需要注意的有一下几点:
1.在设置或者清除 Form Notification 的时候,需要定义一个id,没有特定值,可以是任意字符串,只是用来代表要设置的 message;
2.Form Notification 的 level 有多种,比如:INFO,WARNING,ERROR;
3.当前 Record 可以继续执行保存。