You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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.Page usage: In modern Dynamics 365, Xrm.Page is obsolete. You should use the formContext retrieved from executionContext consistently.
  • Variable typo: object.paymenttamount has an extra "t" — it should be object.paymentamount.
  • Inefficient record retrieval: You’re using retrieveMultipleRecords when you already have the GUID of the specific auto_paymenttype record. Use retrieveRecord instead 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.WebApi call 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, or auto_resitamount are 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

  1. Consistent formContext usage: Replaced all Xrm.Page references with the modern formContext from the execution context.
  2. Proper async handling: We first prevent the save event, run the async lookup, then trigger save manually only if validation passes.
  3. Cleaner GUID handling: Used replace(/[{}]/g, "") to remove the curly braces from the lookup ID, which is required for Web API calls.
  4. Robust null checks: Added checks for empty lookup values and null amount values to avoid runtime errors.
  5. Targeted record retrieval: Used retrieveRecord instead of retrieveMultipleRecords to fetch only the specific payment type record we need, improving performance.
  6. 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 native Xrm.Navigation.openAlertDialog() for a more consistent user experience.
  • Consider adding validation for required fields (e.g., ensure auto_paymentamount and auto_resitamount are filled before saving).
  • Test edge cases: zero amounts, negative amounts (if your business allows them), and empty payment type selections.

内容的提问来源于stack exchange,提问作者Farhan Asyraaf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 08:42:43