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

Dynamics 365中使用JavaScript查询父记录及实现表单保存验证需求求助

Solution for Dynamics 365 JavaScript Requirements

Hey there, let's tackle your two requirements and fix your existing code. I'll break this down step by step:


1. How to Query the Parent Payment Record in JavaScript

Since auto_resittype is a child entity of Payment, your form should have a lookup field linking to the parent Payment record (let's assume the field name is auto_payment; adjust if your actual field name differs). Here's how to retrieve the parent record details:

async function getParentPaymentRecord(executionContext) {
    const formContext = executionContext.getFormContext();
    const parentPaymentLookup = formContext.getAttribute("auto_payment").getValue();
    
    if (parentPaymentLookup) {
        const parentPaymentId = parentPaymentLookup[0].id.replace(/[{}]/g, ""); // Remove curly braces from GUID
        try {
            const parentRecord = await Xrm.WebApi.retrieveRecord("payment", parentPaymentId, "$select=name,auto_adjustmentfield"); // Replace with your actual Payment entity fields
            console.log("Parent Payment Record:", parentRecord);
            // Use parentRecord attributes as needed, e.g., parentRecord.name
        } catch (error) {
            console.error("Error retrieving parent Payment record:", error.message);
        }
    } else {
        console.log("No parent Payment record associated.");
    }
}

2. Fixed Save Validation Logic for auto_resittype Form

Your original code had several issues: using deprecated Xrm.Page, incorrect asynchronous handling, wrong record retrieval (fetching all auto_paymenttype records instead of the linked one), and a typo in variable names. Here's the corrected code with proper validation:

async function resitApproveAmount(executionContext) {
    try {
        const formContext = executionContext.getFormContext();
        const saveEvent = executionContext.getEventArgs();
        
        // Get current form field values
        const paymentAmount = formContext.getAttribute("auto_paymentamount").getValue();
        const resitAmount = formContext.getAttribute("auto_resitamount").getValue();
        const paymentTypeLookup = formContext.getAttribute("auto_paymenttype").getValue();

        // If no payment type linked, allow save (adjust if you require this field to be mandatory)
        if (!paymentTypeLookup) return;

        // Extract GUID of the linked auto_paymenttype record (remove curly braces)
        const paymentTypeId = paymentTypeLookup[0].id.replace(/[{}]/g, "");

        // Retrieve the specific linked auto_paymenttype record to check its name
        const paymentTypeRecord = await Xrm.WebApi.retrieveRecord("auto_paymenttype", paymentTypeId, "$select=auto_name");
        const paymentTypeName = paymentTypeRecord.auto_name;

        // Validate only if payment type is "Credit Account"
        if (paymentTypeName === "Credit Account") {
            // Check if payment amount is greater than resit amount
            if (paymentAmount !== null && resitAmount !== null && paymentAmount > resitAmount) {
                saveEvent.preventDefault(); // Block form save
                Xrm.Navigation.openAlertDialog({ text: "Payment Amount cannot be more than Resit Amount." }); // Use modern alert dialog
                console.log("Save blocked: Payment Amount exceeds Resit Amount.");
            }
            // If validation passes, do nothing - form will save normally
        }

    } catch (error) {
        console.error("Error in resit validation:", error.message);
        // Optionally show an error alert to the user
        Xrm.Navigation.openAlertDialog({ text: "An error occurred during validation: " + error.message });
    }
}

Key Fixes & Improvements:

  • Replaced deprecated Xrm.Page: Uses executionContext.getFormContext() as recommended by Microsoft.
  • Asynchronous Handling: Uses async/await to properly wait for the Xrm.WebApi call to complete before validating, ensuring the save event is only blocked after checking the payment type.
  • Targeted Record Retrieval: Fetches only the linked auto_paymenttype record using its GUID, instead of all records.
  • Modern Alert: Uses Xrm.Navigation.openAlertDialog() instead of alert() for a consistent D365 UI experience.
  • Typo Fix: Corrected paymenttamount to paymentAmount.
  • Null Checks: Added checks for null values in amount fields to avoid unexpected errors.

Setup Instructions:

  1. In your Dynamics 365 environment, open the auto_resittype form editor.
  2. Go to Events tab, add an On Save event handler.
  3. Set the library containing this function, select resitApproveAmount as the function, and check Pass execution context as first parameter.
  4. Publish your customizations.

内容的提问来源于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:18:13