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

Dynamics 365左侧导航特定记录链接代码修改求助

Dynamics 365导航栏链接打开特定记录的优化方案

问题背景

在Dynamics 365左侧导航栏添加Web资源链接,目标是打开与当前用户关联的特定记录,但现有代码存在问题:

  • 使用window.location.href跳转时,会加载完整的应用框架(包含重复导航栏),而非仅目标记录表单
  • 注释的window.open会在新标签页打开,不符合主应用内打开的需求

解决方案

改用Dynamics 365官方提供的Xrm.Utility.openEntityForm方法,该方法会在当前应用上下文内直接打开记录表单,不会重复加载应用框架。

修改后的完整代码

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function ensureXrmLoaded(callback) {
            if (typeof window.top.Xrm !== 'undefined' && window.top.Xrm.Utility) {
                callback();
            } else {
                console.log('Xrm is not loaded yet, retrying...');
                setTimeout(function() {
                    ensureXrmLoaded(callback);
                }, 500);  // Increased delay to 500ms
            }
        }

        async function getCurrentUserId() {
            try {
                const response = await fetch(window.top.Xrm.Utility.getGlobalContext().getClientUrl() + '/api/data/v9.1/WhoAmI', {
                    headers: {
                        'OData-MaxVersion': '4.0',
                        'OData-Version': '4.0',
                        'Accept': 'application/json',
                        'Content-Type': 'application/json; charset=utf-8'
                    }
                });

                if (response.ok) {
                    const data = await response.json();
                    console.log('User ID:', data.UserId);
                    return data.UserId;
                } else {
                    throw new Error('Error retrieving current user ID: ' + response.statusText);
                }
            } catch (error) {
                console.error(error);
                throw error;
            }
        }

        async function getRecordIdForCurrentUser(userId) {
            try {
                const query = `/api/data/v9.1/new_tutorstrainersandmentors?$filter=_new_systemuser_value eq ${userId}`;
                const response = await fetch(window.top.Xrm.Utility.getGlobalContext().getClientUrl() + query, {
                    headers: {
                        'OData-MaxVersion': '4.0',
                        'OData-Version': '4.0',
                        'Accept': 'application/json',
                        'Content-Type': 'application/json; charset=utf-8'
                    }
                });

                if (response.ok) {
                    const data = await response.json();
                    if (data.value.length > 0) {
                        console.log('Record ID:', data.value[0].new_tutorstrainersandmentorid);
                        return data.value[0].new_tutorstrainersandmentorid;
                    } else {
                        throw new Error('No matching records found.');
                    }
                } else {
                    throw new Error('Error retrieving related record: ' + response.statusText);
                }
            } catch (error) {
                console.error(error);
                throw error;
            }
        }

        async function openCustomForm() {
            try {
                const userId = await getCurrentUserId();
                const recordId = await getRecordIdForCurrentUser(userId);
                const formId = '769d1133-1a2c-ef11-840a-000d3a655ff1'; // 替换为实际表单ID
                const entityName = 'new_tutorstrainersandmentor';

                // 使用官方API在主应用内打开表单
                window.top.Xrm.Utility.openEntityForm(
                    entityName,
                    recordId,
                    null, // 可选参数,可传递额外表单参数
                    { formId: formId } // 指定要打开的表单ID
                );
            } catch (error) {
                console.error('Error opening custom form:', error);
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM fully loaded and parsed');
            ensureXrmLoaded(openCustomForm);
        });
    </script>
</head>
<body>
</body>
</html>

关键修改说明

  1. 替换跳转逻辑:移除了手动拼接URL和window.location.href的代码,改用window.top.Xrm.Utility.openEntityForm
  2. 参数对应:原URL中的实体名称、记录ID、表单ID参数,直接映射到API的参数中
  3. 上下文保持:通过window.top调用顶层的Xrm对象,确保在Web资源的iframe上下文内正确访问Dynamics 365的全局API

内容的提问来源于stack exchange,提问作者Martin Hutchins

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:33:21