我为下面提到的场景创建了触发器,我想要解决方案。 - apex,salesforce

时间:2018-01-22 12:13:49

标签: triggers salesforce apex-code apex apex-trigger

有两个对象:基金和机会。和机会对象有一个基金查找。我已经开发了一个触发器,它总结了所有相对机会的总量,并在基金对象的自定义字段中设置了该金额。现在我的代码中存在的一个问题是,每当我尝试使用包含多个基金数据的CSV文件创建批量商机时,它总计所有基金的总额并将其设置为仅在第一个记录基金ID中。我需要使用Map的解决方案。 谢谢。

触发:

trigger newLeadTrigger on Opportunity (after insert , after update, after delete , after undelete) {

    if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate || trigger.isUndelete)){
           OpportunityCustomRollup.CountRollup(Trigger.new);
    }

    if(Trigger.isDelete)
    {
        OpportunityCustomRollup.CountRollup(Trigger.old);
    }
}

控制器类:

public class OpportunityCustomRollup {

    public static void CountRollup(List<Opportunity> lstOpportunity){

        set<id> oppIds = new set<id>();
        map<string, integer> classroomIDToDeskCountMap = new map<string, integer>();
        id objrecordtypeid = [SELECT Id FROM RecordType WHERE DeveloperName ='Fund_Raising'].Id;
        double amount = 0;

        try {
                for (Opportunity objOpportunity : lstOpportunity){
                    oppIds.add(objOpportunity.Fund__c);
                }

                Fund__c objfund = [SELECT Id, Total_opportunity_amount__c  FROM Fund__c WHERE Id = :oppIds];
                List<Opportunity> list_Opportunity = [SELECT Id, Amount FROM Opportunity WHERE Fund__c = :objfund.Id and StageName = 'Closed Won' and RecordTypeId =: objrecordtypeid];


                 for(Opportunity AmountOpportunity : list_Opportunity) {
                        amount += AmountOpportunity.amount; 
                 }


                  objfund.Total_opportunity_amount__c = amount;
                  update objfund;   
            } 


        catch (Exception e) {
                System.debug(e);
            }

    }

}

1 个答案:

答案 0 :(得分:1)

这应该会给你一些想法,但你必须自己试验一下。使用更新的代码编辑您的问题,如果您仍然卡住,请给我发表评论。

// This is just for testing because when executing standalone apex code
// you don't have trigger.new. Modify the query as you want.

List<Opportunity> lstOpportunity = [SELECT Id
     FROM Opportunity
     WHERE StageName = 'Closed Won' and RecordType.DeveloperName = 'Fund_Raising'
     LIMIT 10];


List<Fund__c> funds = new List<Fund__c>();
for(AggreateResult ar : [SELECT SUM(Amount) amt, Fund__c fund
    FROM Opportunity
    WHERE Id IN :lstOpportunity
        AND StageName = 'Closed Won' and RecordType.DeveloperName = 'Fund_Raising'
        AND Fund__c != null
    GROUP BY Fund__c]){
    Fund__c f = new Fund__c(
        Id = (Id) ar.get('fund'),
        Total_opportunity_amount__c = (Decimal) ar.get('amt')
    );

    funds.add(fund);
}
update funds;

P.S。在appexchange上查看此应用:https://appexchange.salesforce.com/appxListingDetail?listingId=a0N30000009i3UpEAI 我不隶属于他们,但如果你是管理员,配置它可能比编写代码,单元测试更容易..