【问题标题】:Salesforce:Add record to a field which is dependent on the input of other fieldSalesforce:将记录添加到依赖于其他字段输入的字段
【发布时间】:2012-02-08 19:06:38
【问题描述】:

我有一个名为“Salary”的对象。其中包含三个字段-“添加薪水”、“月”和“可用薪水”。还有从 Salary 对象到“用户名”对象的查找关系。每个用户都有每个月的工资记录。每当将薪水添加到特定用户的记录时,可用薪水应显示前几个月的薪水总和。我怎样才能做到这一点??请建议我....谢谢。

【问题讨论】:

    标签: salesforce apex-code visualforce


    【解决方案1】:

    最简单的方法是将查找关系更改为主-详细信息关系并在用户对象上使用Roll-Up Summary 字段(设置 > 自定义 > 用户 > 字段 > 用户自定义字段 > 新建)。

    或者,您可以在 Salary 对象上使用 Trigger,但只有在您绝对需要无法通过汇总摘要或其他配置完成的附加功能时才这样做。

    这是使用触发器的示例。没试过编译,难免会出现一些编译错误,不过是个开始的地方。

    trigger AddSalary on Salary__c (after update) {
    
        // create a set of all the unique User Ids
        Map<Id,List<Salary__c>> SalaryByUserId = new Map<Id,List<Salary__c>>();
        for(Salary__c s : Trigger.new)
        {
            List<Salary__c> SalariesForUser = SalaryByUserId.get(s.User__c);
    
            if(SalariesForUser == null) 
            { 
                SalaryByUserId.put(s.User__c,new Salary__c[]{s}); 
            }
            else
            {
                SalariesForUser.add(s);
                SalaryByUserId.put(s.User__c,SalariesForUser); 
            }
        }
    
        // query for all the User records for the unique UserIds in the records
        // create a map for a lookup / hash table for the User info
        Map<Id,User> Users = new Map<Id,User>(
            [Select Id, Username, Available_Salary__c From User Where Id IN SalaryByUserId.keyset()]);
    
        // iterate over the list of records being processed in the Trigger and add the Salaries to the Users
        for (Id i : SalaryByUserId.keyset())
        {
            User u = Users.get(i);
            Decimal TotalSalary = 0;
    
            for(Salary__c s : SalaryByUserId.get(u.Id))
            {
                TotalSalary += s.Monthly_Salary__c;
            }
    
            Users.get(u.Id).Total_Salary__c = TotalSalary;
        }
    
        update Users;
    
    }
    

    【讨论】:

    • 如何使用汇总字段??它仅在两个对象之间存在主从关系时才有效。在触发器中,如果我将 available_salary__c 字段初始化为零,则每次创建新记录时它都等于零。因此,我无法添加前几个月的工资。请告诉我如何进行。谢谢
    • 为什么不将 Lookup 更改为 Master-Detail 关系?
    • 我无法将其设为 Master-detail,因为我的应用程序中还有其他功能。如果我只有 b/w 对象的查找关系,我还能做其他事情吗??
    猜你喜欢
    • 2016-06-18
    • 2017-09-09
    • 2022-01-14
    • 2022-08-05
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2022-09-28
    • 2012-04-14
    相关资源
    最近更新 更多