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

如何使用Lightning和Aura Component实现两级账户展示的SalesForce DataTable

实现双DataTable关联展示账户层级的方案

1. Aura组件属性定义

首先在.cmp文件中声明所需存储变量和表格列配置:

<aura:attribute name="level1Accounts" type="List" />
<aura:attribute name="level2Accounts" type="List" />
<aura:attribute name="selectedLevel1Id" type="String" />
<!-- 一级账户表格列配置,内置切换子账户按钮 -->
<aura:attribute name="level1Columns" type="List" default="[
    {label: '一级账户名称', fieldName: 'Name', type: 'text'},
    {type: 'button', typeAttributes: {label: '查看关联二级账户', name: 'load_level2', disabled: false}}
]" />
<aura:attribute name="level2Columns" type="List" default="[
    {label: '二级账户名称', fieldName: 'Name', type: 'text'},
    {label: '关联一级账户', fieldName: 'Parent.Name', type: 'text'}
]" />

2. 页面布局配置

嵌套两个DataTable组件,二级表格可设置仅选中一级账户后展示:

<!-- 一级账户表格 -->
<lightning:datatable
    keyField="Id"
    data="{!v.level1Accounts}"
    columns="{!v.level1Columns}"
    onrowaction="{!c.handleLevel1RowAction}"
    hideCheckboxColumn="true"
/>

<!-- 二级账户表格 -->
<aura:if isTrue="{!not(empty(v.selectedLevel1Id))}">
    <div class="slds-m-top_medium">
        <lightning:datatable
            keyField="Id"
            data="{!v.level2Accounts}"
            columns="{!v.level2Columns}"
            hideCheckboxColumn="true"
        />
    </div>
</aura:if>

3. 前端控制器逻辑

在Controller.js中实现行按钮点击事件,调用后端接口拉取关联二级账户:

handleLevel1RowAction : function(component, event, helper) {
    const action = event.getParam('action');
    const selectedRow = event.getParam('row');
    if(action.name === 'load_level2'){
        component.set('v.selectedLevel1Id', selectedRow.Id);
        // 调用Apex接口
        const apexAction = component.get('c.getRelatedLevel2Accounts');
        apexAction.setParams({
            parentAccountId : selectedRow.Id
        });
        apexAction.setCallback(this, function(response){
            if(response.getState() === 'SUCCESS'){
                component.set('v.level2Accounts', response.getReturnValue());
            }
        });
        $A.enqueueAction(apexAction);
    }
}

4. 后端Apex接口实现

编写带权限校验的查询方法,返回关联的二级账户数据:

@AuraEnabled(cacheable=true)
public static List<Account> getRelatedLevel2Accounts(String parentAccountId){
    if(String.isBlank(parentAccountId)){
        return new List<Account>();
    }
    return [
        SELECT Id, Name, Parent.Name 
        FROM Account 
        WHERE ParentId = :parentAccountId
        WITH SECURITY_ENFORCED
    ];
}

可选扩展功能

  • 如需支持切换回全量二级账户展示,可新增一个显示全部二级账户按钮,点击后清空selectedLevel1Id,调用接口查询所有ParentId != null的账户即可
  • 可给选中的一级账户行添加高亮样式,优化交互体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:18:03