如何使用JavaScript查询父级支付记录并实现实体表单金额校验逻辑(附代码求审核)
Analysis and Corrected Code for Your Dynamics 365 Form Validation
Let’s walk through your existing code, fix the issues, and make sure it properly meets your requirements (querying the parent payment type record and enforcing the amount validation rule).
Key Issues in Your Current Code
- Deprecated
Xrm.Pageusage: In modern Dynamics 365,Xrm.Pageis obsolete. You should use theformContextretrieved fromexecutionContextconsistently. - Variable typo:
object.paymenttamounthas an extra "t" — it should beobject.paymentamount. - Inefficient record retrieval: You’re using
retrieveMultipleRecordswhen you already have the GUID of the specificauto_paymenttyperecord. UseretrieveRecordinstead to fetch just the single record you need. - Unnecessary manual save: When validation passes, you don’t need to call
object.fctx.data.save()explicitly — the original save flow will resume if you don’t prevent it. - Async handling gap: The
Xrm.WebApicall is asynchronous. If you don’t first prevent the save event, the form might save before your validation logic runs. - Missing null checks: You don’t handle cases where
auto_paymenttype,auto_paymentamount, orauto_resitamountare empty, which could cause errors.
Corrected JavaScript Code
function resitApproveAmount(executionContext) { try { const formContext = executionContext.getFormContext(); const saveEventArgs = executionContext.getEventArgs(); // Get form values with null checks const paymentAmount = formContext.getAttribute("auto_paymentamount").getValue(); const resitAmount = formContext.getAttribute("auto_resitamount").getValue(); const paymentTypeLookup = formContext.getAttribute("auto_paymenttype").getValue(); // If payment type isn't selected, allow save to proceed if (!paymentTypeLookup || paymentTypeLookup.length === 0) { return; } // Prevent save initially to wait for async validation saveEventArgs.preventDefault(); const paymentTypeId = paymentTypeLookup[0].id.replace(/[{}]/g, ""); // Clean GUID braces // Retrieve the specific payment type record Xrm.WebApi.retrieveRecord("auto_paymenttype", paymentTypeId, "$select=auto_name").then( function success(result) { const paymentTypeName = result.auto_name; // Only apply validation if payment type is "Credit Account" if (paymentTypeName === "Credit Account") { // Check if payment amount is valid (ensure values are not null first) if (paymentAmount !== null && resitAmount !== null) { if (paymentAmount > resitAmount) { alert("Payment Amount cannot be more than Resit Amount."); } else { // Validation passed, trigger save manually formContext.data.save().then( function () { // Optional: Success callback if needed }, function (error) { console.log("Save failed: " + error.message); } ); } } else { // If either amount is missing, allow save or add a warning as needed formContext.data.save(); } } else { // Payment type isn't "Credit Account", allow save formContext.data.save(); } }, function (error) { console.log("Error retrieving payment type: " + error.message); // Optionally re-enable save or show error to user alert("Failed to validate payment type. Please try again."); } ); } catch (error) { console.log("Unexpected error: " + error.message); alert("An error occurred during validation. Please contact support."); } }
Improvements Explained
- Consistent
formContextusage: Replaced allXrm.Pagereferences with the modernformContextfrom the execution context. - Proper async handling: We first prevent the save event, run the async lookup, then trigger save manually only if validation passes.
- Cleaner GUID handling: Used
replace(/[{}]/g, "")to remove the curly braces from the lookup ID, which is required for Web API calls. - Robust null checks: Added checks for empty lookup values and null amount values to avoid runtime errors.
- Targeted record retrieval: Used
retrieveRecordinstead ofretrieveMultipleRecordsto fetch only the specific payment type record we need, improving performance. - Clearer flow: The logic is structured to handle different scenarios (missing values, non-Credit Account types) explicitly.
Additional Recommendations
- Replace
alert()with Dynamics 365’s nativeXrm.Navigation.openAlertDialog()for a more consistent user experience. - Consider adding validation for required fields (e.g., ensure
auto_paymentamountandauto_resitamountare filled before saving). - Test edge cases: zero amounts, negative amounts (if your business allows them), and empty payment type selections.
内容的提问来源于stack exchange,提问作者Farhan Asyraaf
相关产品推荐
相关产品推荐

