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

如何通过Web资源JavaScript获取视图当前的FetchXML值?

获取当前视图的FetchXML并批量处理可见记录

实现思路

要实现对当前视图可见记录的批量操作,核心是通过Dynamics 365/Power Apps客户端API获取用户修改后的视图FetchXML,再基于该FetchXML查询所有符合条件的记录,最后执行自定义操作。

具体实现代码与步骤

1. 获取当前列表的Grid控件

这是获取视图信息的基础入口,兼容统一接口(Unified Interface)与经典UI:

function getCurrentGrid() {
    // 优先获取统一接口下的主控件
    const gridContext = Xrm.Page.getControl("primaryControl");
    if (gridContext && gridContext.getGrid) {
        return gridContext.getGrid();
    }
    // 兼容经典UI的Grid控件
    const classicGrid = Xrm.Page.getControl("grid");
    return classicGrid ? classicGrid : null;
}

2. 提取当前视图的FetchXML

通过Grid控件的视图选择器,获取用户当前使用的视图对象,从中提取实时的FetchXML:

function getCurrentViewFetchXml() {
    const grid = getCurrentGrid();
    if (!grid) return null;

    const viewSelector = grid.getViewSelector();
    const currentView = viewSelector.getCurrentView();
    
    // currentView.fetchXml即为用户当前视图的查询语句(包含筛选、排序等修改)
    return currentView.fetchXml;
}

3. 批量查询并处理记录

拿到FetchXML后,调用Web API批量获取所有符合条件的记录,再循环执行目标操作:

async function processVisibleRecords() {
    const fetchXml = getCurrentViewFetchXml();
    if (!fetchXml) {
        console.error("无法获取当前视图的FetchXML");
        Xrm.Utility.alertDialog("获取视图信息失败,请重试");
        return;
    }

    try {
        // 用FetchXML查询所有符合条件的记录,自动处理分页
        const response = await Xrm.WebApi.retrieveMultipleRecords(
            "entityLogicalName", 
            `?fetchXml=${encodeURIComponent(fetchXml)}`
        );
        
        // 循环处理每条记录,替换为你的实际操作逻辑
        for (const record of response.entities) {
            // 示例:更新记录字段
            await Xrm.WebApi.updateRecord("entityLogicalName", record.id, {
                "fieldX": "newValue"
            });
            console.log(`已处理记录ID: ${record.id}`);
        }

        Xrm.Utility.alertDialog("所有可见记录处理完成");
    } catch (error) {
        console.error("处理记录出错:", error);
        Xrm.Utility.alertDialog(`处理失败:${error.message || "未知错误"}`);
    }
}

4. 功能区按钮绑定

将processVisibleRecords函数绑定到功能区按钮的命令中,同时设置按钮启用规则:仅在列表视图页面且Grid控件存在时启用。

关键注意事项

  • 分页兼容:retrieveMultipleRecords会自动处理分页(默认每页50条),若需手动控制分页逻辑,可通过response.nextLink递归调用接口。
  • 性能优化:若处理超大量记录(上千条),建议使用ExecuteMultipleRequest批量操作API,减少网络请求次数。
  • 权限校验:确保操作账号拥有目标实体的对应权限(如更新、删除权限),避免执行失败。
  • API版本适配:最新模型驱动应用中,可使用Xrm.App.getGridContext("primaryControl")替代Xrm.Page相关方法,适配更现代的API规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 22:27:19