function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
VempallyVempally 

need help with the following trigger

Hi everyone...
 
trigger CustomRollupSummary on Contact (after insert, after update, after delete, after undelete) {
	
    if(trigger.isInsert && Trigger.isAfter){
    List<Account> lst_accounts = new list<Account>();
    //decimal Value =0;
    set<id> account_ids = new set<id>();
    for(Contact c : trigger.new){
        account_ids.add(c.accountid);
        system.debug('account_ids' + account_ids);
    }
    Map<id, Account> map_accounts = new Map<id, Account>([select id, name from Account where id in : account_ids]);
    system.debug('map_accounts' + map_accounts);
    system.debug('map_accounts' + map_accounts.values());
        for(Account a : map_accounts.values()){
        system.debug('account' + a);
        a.Amount_Sum__c = 0;
    	//for(Contact c :[select id, name, amount__c from contact where accountid =: a.Id])
        for(Contact c : a.contacts)
    {
       system.debug('Contact' + c);
       
       a.Amount_Sum__c += c.amount__c;
    
    }
            lst_accounts.add(a);
    }
    system.debug('updated accounts' + lst_accounts);
    update lst_accounts;
    }
   /* List<Contact> lst_contacts = new  List<Contact>();
    for(Account a : lst_account){
        lst_contacts.add(a.contacts);
    	system.debug('lst_contacts');
    */
}

In the for loop where iam retrieving contacts based on an account, when SOQL is used its working fine but when the soql is replaced with a a.contacts the for loop is not getting executed... Why...?

 
DebasisDebasis
HI vempally,

when you are fetching accounts, you need to use relationship query to have contacts. I have added relationship query in your code so thats your map_accounts wil hold all related contacts as below 
Map<id, Account> map_accounts = new Map<id, Account>([select id, name,(select amount__c,id from contacts) from Account where id in : account_ids]);
 
trigger CustomRollupSummary on Contact (after insert, after update, after delete, after undelete) {
	
    if(trigger.isInsert && Trigger.isAfter){
		List<Account> lst_accounts = new list<Account>();
		//decimal Value =0;
		set<id> account_ids = new set<id>();
		for(Contact c : trigger.new){
			account_ids.add(c.accountid);
			system.debug('account_ids' + account_ids);
		}
		Map<id, Account> map_accounts = new Map<id, Account>([select id, name,(select amount__c,id from contacts) from Account where id in : account_ids]);
		system.debug('map_accounts' + map_accounts);
		system.debug('map_accounts' + map_accounts.values());
        for(Account a : map_accounts.values()){
			system.debug('account' + a);
			a.Amount_Sum__c = 0;
			//for(Contact c :[select id, name, amount__c from contact where accountid =: a.Id])
			for(Contact c : a.contacts)
			{
				   system.debug('Contact' + c);
				   
				   a.Amount_Sum__c += c.amount__c;
		
			}
			 lst_accounts.add(a);
	}
    system.debug('updated accounts' + lst_accounts);
    update lst_accounts;
    }
   /* List<Contact> lst_contacts = new  List<Contact>();
    for(Account a : lst_account){
        lst_contacts.add(a.contacts);
    	system.debug('lst_contacts');
    */
}

please check this and let me know if it helps you.

Thanks,
Debasis
DebasisDebasis
Hi Vempally,

If i have understood your trigger in correct way then I think you camn use below code for it. We no need to fire another query to fetch the account to update its amount_sum__c field.
trigger CustomRollupSummary on Contact (after insert, after update, after delete, after undelete) {
map<id,Account> accountMapToUpdate = new map<id,Account>();
for(contact con:trigger.new){
	
	if(con.accountid!=null){
		
		if(accountMapToUpdate.get(con.accountid)!=null){
			accountMapToUpdate.get(con.accountid,acc).Amount_Sum__c+=con.amount__c;
		}
		else{
			Account acc = new Account(id=con.accountId);
			acc.Amount_Sum__c=con.amount__c;
			accountMapToUpdate.put(con.accountid,acc);
		}
		
	}
}
if(accountMapToUpdate.size()>0){
	update accountMapToUpdate.values();
}
}

please use this optimized code and let me know if it helps you.
Mahesh DMahesh D
Hi Vempally,

Please find the below trigger:

Here I handled:

(1) Corrected the Logic.
(2) Naming convention.
(3) Alignment.
(4) Considered all possible scenarios.
(5) Tested the solution in my DE environment and looks good.

 
//
// CustomRollupSummary trigger to handle the roll up summary on Account
//
trigger CustomRollupSummary on Contact (after insert, after delete, after undelete, after update) {
    set<Id> accIdSet = new set<Id>();
    
    if(trigger.isinsert || trigger.isUpdate || trigger.Isundelete){
        for(Contact con: Trigger.new){
            if(Trigger.isInsert || Trigger.isUndelete || (con.AccountId != Trigger.oldMap.get(con.Id).AccountId || 
                                                            con.Amount__c != Trigger.oldMap.get(con.Id).Amount__c))
                accIdSet.add(con.AccountId);
        }
    }
    
    if(trigger.isUpdate || trigger.isDelete) {
        for(Contact con: Trigger.old){
            if(Trigger.isDelete || (con.AccountId != Trigger.newMap.get(con.Id).AccountId ||
                                        con.Amount__c != Trigger.newMap.get(con.Id).Amount__c))
                accIdSet.add(con.AccountId);
        }
    }    
    
    if(!accIdSet.isEmpty()) {
        List<Account> accList = [select Id, Amount_Sum__c, (Select Id, Amount__c from Contacts) from Account Where ID IN: accIdSet];
        
        for(Account acc : accList){
            acc.Amount_Sum__c = 0;
            for(Contact con : acc.Contacts) {
                acc.Amount_Sum__c += (con.Amount__c != null ? con.Amount__c : 0);
            }
            
        }
        update accList;
    }
}

Above trigger will not work if you modify the Account on the Contact. When we modify the Account on Contact we have to re-calculate the Rollup summary on both new and old Accounts.

Please do let me know if it helps you.

Regards,
Mahesh
JyothsnaJyothsna (Salesforce Developers) 
Hi,

Please try the below sample code.
 
trigger ContactCount on Contact (after insert, after update, after delete) {
    Map<Id, List<Contact>> AcctContactList = new Map<Id, List<Contact>>();
    Set<Id> AcctIds = new Set<Id>();    
    List<Account> AcctList = new List<Account>();
    List<Contact> ConList = new List<Contact>();
    
    if(trigger.isInsert || trigger.isUPdate) {
        for(Contact Con : trigger.New) {
            if(String.isNotBlank(Con.AccountId)){
                AcctIds.add(Con.AccountId);  
            }   
        }  
    }
    
    if(trigger.isDelete || trigger.isUPdate) {
        for(Contact Con : trigger.Old) {
            AcctIds.add(Con.AccountId);     
        }  
    }           
    
    if(AcctIds.size() > 0){
        ConList = [SELECT Id, AccountId FROM Contact WHERE AccountId IN : AcctIds];
        
        for(Contact Con : ConList) {
            if(!AcctContactList.containsKey(Con.AccountId)){
                AcctContactList.put(Con.AccountId, new List<Contact>());
            }
            AcctContactList.get(Con.AccountId).add(Con);      
        }                           
        
        System.debug('Account Id and Contact List Map is ' + AcctContactList);
            
        AcctList = [SELECT No_of_contacts__c FROM Account WHERE Id IN : AcctIds];
        
        for(Account Acc : AcctList) {
            List<Contact> ContList = new List<Contact>();
            ContList = AcctContactList.get(Acc.Id);
            Acc.No_of_contacts__c= ContList.size();
        }    
        
        System.debug('Account List is ' + AcctList);
        update AcctList;    
    }

}

Hope this helps you!
Best Regards,
Jyothsna
VempallyVempally
Hi Everyone

How to find min, max values...?