+ Start a Discussion
anil Anil5anil Anil5 

How to write trigger.bellow requirement,any forward link or code

trigger act as Rollupsumary functionality(sum,count,min,max) for lookup Relationship between two object with bestpractices
 
Andy BoettcherAndy Boettcher
The first thing that I would ask is "if these two objects are Master/Detail, please do not write a trigger - use the declarative Roll Up functionality."

If they're not related - your trigger is going to use these:  https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_agg_fns.htm
omm ommomm omm
This is a sample trigger which counts number of contacts for each account 

trigger ContactCount on Contact (after insert, after update, after delete, after undelete) {
    Map<Id, List<Contact>> mapAcctIdContactList = new Map<Id, List<Contact>>();
    Map<Id, List<Contact>> mapAcctIdDelContactList = new Map<Id, List<Contact>>();
    Set<Id> AcctIds = new Set<Id>();    
    List<Account> listAcct = new List<Account>();
    
    if(trigger.isInsert) {
        for(Contact Con : trigger.New) {
            if(String.isNotBlank(Con.AccountId)) {
                if(!mapAcctIdContactList.containsKey(Con.AccountId)) {
                    mapAcctIdContactList.put(Con.AccountId, new List<Contact>());
                }
                mapAcctIdContactList.get(Con.AccountId).add(Con); 
                AcctIds.add(Con.AccountId);
            }   
        }  
    }
    
    if(trigger.isUpdate) {
        for(Contact Con : trigger.New) {
            if(String.isNotBlank(Con.AccountId) && Con.AccountId != trigger.oldMap.get(Con.Id).AccountId) {
                if(!mapAcctIdContactList.containsKey(Con.AccountId)){
                    mapAcctIdContactList.put(Con.AccountId, new List<Contact>());
                }
                mapAcctIdContactList.get(Con.AccountId).add(Con); 
                AcctIds.add(Con.AccountId);
            } else if(String.isBlank(Con.AccountId) && String.isNotBlank(trigger.oldMap.get(Con.Id).AccountId)) {
                if(!mapAcctIdDelContactList.containsKey(Con.AccountId)){
                    mapAcctIdDelContactList.put(Con.AccountId, new List<Contact>());
                }
                mapAcctIdDelContactList.get(Con.AccountId).add(Con);   
                AcctIds.add(trigger.oldMap.get(Con.Id).AccountId);
            }
        }  
    }
    
    if(trigger.isUndelete) {
        for(Contact Con : trigger.new) {
            if(String.isNotBlank(Con.AccountId)){
                if(!mapAcctIdContactList.containsKey(Con.AccountId)){
                    mapAcctIdContactList.put(Con.AccountId, new List<Contact>());
                }
                mapAcctIdContactList.get(Con.AccountId).add(Con);     
                AcctIds.add(Con.AccountId);
            }
        }  
    }      

    if(trigger.isDelete) {
        for(Contact Con : trigger.Old) {
            if(String.isNotBlank(Con.AccountId)){
                if(!mapAcctIdDelContactList.containsKey(Con.AccountId)){
                    mapAcctIdDelContactList.put(Con.AccountId, new List<Contact>());
                }
                mapAcctIdDelContactList.get(Con.AccountId).add(Con);    
                AcctIds.add(Con.AccountId); 
            }
        }  
    }   
    
    if(AcctIds.size() > 0) {
        listAcct = [SELECT Id, Number_of_Contacts__c FROM Account WHERE Id IN : AcctIds];
        
        for(Account acct : listAcct) {
            Integer noOfConts = 0;
            if(mapAcctIdContactList.containsKey(acct.Id)) {
                noOfConts += mapAcctIdContactList.get(acct.Id).size();
            }
            if(mapAcctIdDelContactList.containsKey(acct.Id)) {
                noOfConts -= mapAcctIdDelContactList.get(acct.Id).size();
            }
            acct.Number_of_Contacts__c = acct.Number_of_Contacts__c == null ? noOfConts : (acct.Number_of_Contacts__c + noOfConts);
        }
        
        update listAcct;    
    }
}
omm ommomm omm
This is a sample trigger which does total ammount . This may help you 


trigger TotalAmountRollup on Opportunity (after insert,after update,after delete,before update) { /*map<id,opportunity> oppmap=new map<id,opportunity>(); if(trigger.isinsert) { for(opportunity opp:trigger.new) { oppmap.put(opp.accountid,opp); } } if(trigger.isupdate ||trigger.isdelete) { for(opportunity opp:trigger.old) { oppmap.put(opp.accountid,opp); } } map<id,account> accmap=new map<id,account>([select id,name,Total_Amount__c from account where id in :oppmap.keySet()]); List<Account> toUpdate=new List<Account>(); for(account acc:[select id,name,Total_Amount__c,(select id,name,amount from opportunities) from account where id in :oppmap.keySet()]) { decimal count=0; for(integer i=0;i<acc.opportunities.size();i++) { count=count+ acc.opportunities[i].amount; } accmap.get(acc.id).total_Amount__c=count; toUpdate.add(accmap.get(acc.id)); } update toUpdate; */ TotalAMountEventHandler.SomeMethod(Trigger.new,Trigger.old, Trigger.isInsert, Trigger.IsUpdate, Trigger.IsDelete) ; TotalAMountEventHandler v=new TotalAMountEventHandler(); v.BeforeUpdate(Trigger.new); } =================================================================================================================================================== public class TotalAMountEventHandler { public static void SomeMethod(List<opportunity> newOpp,List<Opportunity> oldOpp,Boolean IsInsert,Boolean IsUpdate,Boolean IsDelete) { set<id> oppAccId=new set<id>(); if(IsInsert) { for(Opportunity op:newOpp) { oppAccId.add(op.AccountId); } } if(IsUpdate||IsDelete) { for(Opportunity o:oldOpp) { oppAccId.add(o.AccountId); } } Map<Id,Account> amap=new Map<Id,Account>([select id,name from account where id in:oppAccId]); List<Account> toUpdate=new List<Account>(); for(Account a:[select id,name,(select id,AccountId,amount from opportunities),total_Amount__c from account where id in:oppAccId]) { decimal count=0; if(amap.containsKey(a.id)) { for(integer i=0;i<a.opportunities.size();i++) { count=count+a.opportunities[i].amount; } } amap.get(a.id).total_Amount__c=count; toUpdate.add(amap.get(a.id)); } update toUpdate; } public void BeforeUpdate(List<Opportunity> newOpp) { for(Opportunity o:newOpp) { if(o.Description==null) { o.Description='From Trigger In Event Handler'; } } } }