2012-02-08 70 views
-1

我有一個名爲「Salary」的對象。它有三個字段 - 「添加薪水」,「月」和「可用薪資」。此外還有一個從Salary對象到'用戶名'對象的查找關係。每個用戶都有一個月薪表。無論何時將薪水添加到特定用戶的記錄中,可用薪水應顯示前幾個月的薪水總和。我怎樣才能做到這一點??請建議我....謝謝。Salesforce:將記錄添加到依賴於其他字段輸入的字段

回答

0

最簡單的方法是將查找關係更改爲主從關係,並在用戶對象上使用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; 

} 
+0

如何使用匯總彙總字段?只有在兩個對象之間存在主細節關係的情況下才有效。在觸發器中,如果我用0初始化available_salary__c字段,則每次創建新記錄時它都等於零。所以,我無法增加前幾個月的薪水。請告訴我如何繼續。謝謝 – aset01 2012-02-08 20:15:43

+0

爲什麼不將查找更改爲主 - 明細關係? – 2012-02-08 20:19:11

+0

因爲在我的應用程序中還有其他功能,所以我無法將它作爲主細節。如果我只有查找關係b/w對象,我可以做其他事情嗎? – aset01 2012-02-08 20:21:18