Skip to main content
Hi all , Apex Trigger on Account which adds all the Closed won Opportunity amounts of that Account and shows it on the Account record. , can any one help me writing the trigger for updating account field 
6 个回答
  1. 2021年8月20日 08:06
    Hii Brucelee

    Try Below Trigger

    A: Insert Method If Opportunity Is Created With Related To Account And Stage Closed Won  And Amount Is Not null Total Amount Updated

    B: Update Method  if Already Created Opportunity Is Updated With Diff Account or Any Change in Amount  Total Amount Updated

    trigger SumAmountOpp on Opportunity (After Insert,After Update,After Delete) {

    List<Account> accList=new List<Account>();

    Set<Id> setAccIds = new Set<Id>();

    if(Trigger.isInsert){

    if(trigger.isAfter){

    for(Opportunity con : Trigger.new){

    if(con.AccountId != null && Con.StageName == 'Closed Won' && con.Amount != null){

    setAccIds.add(con.AccountId);

    }

    }

    }

    }

    system.debug('setAccIds ==> '+setAccIds);

    if(Trigger.isUpdate){

    if(trigger.isAfter){

    for(Opportunity con : Trigger.new){

    if(con.AccountId!=Trigger.oldMap.get(con.Id).AccountId && Con.StageName == 'Closed Won' && con.Amount != null){

    setAccIds.add(con.AccountId);

    setAccIds.add(Trigger.oldMap.get(con.Id).AccountId);

    }

    else if(Con.StageName == 'Closed Won' && con.Amount!=Trigger.oldMap.get(con.Id).Amount && con.AccountId != null){

    setAccIds.add(con.AccountId);

    }

    }

    }

    }

    if(Trigger.isDelete){

    if(trigger.isAfter){

    for(Opportunity con : Trigger.old) {

    if(con.AccountId != null && Con.StageName == 'Closed Won'){

    setAccIds.add(con.AccountId);

    }

    }

    }

    }

    for(Account acc :[Select id,Total_Amount__c ,(Select id,Name,Amount from Opportunities where StageName = 'Closed Won') from Account where Id in : setAccIds]){

    integer val = 0;

    for(Opportunity con : acc.Opportunities){

    val += integer.valueOf(con.Amount);

    system.debug('====> ' +val);

    }

    system.debug(val);

    acc.Total_Amount__c = string.valueOf(val);

    acclist.add(acc);

    }

    if(acclist.size()>0){

    update accList;

    }

    }

    Please Mark It As Best Answer If It Helps

    Thank You!
0/9000