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
Rohan SRohan S 

Want to create a roll up summary in a look-up relationship

On Account object I want a field (NumberOfContacts__c) to show the number of associated child Contacts. Can someone please help me with the Apex Class for this trigger which should work in all DML operations such as Create, Update, Delete and UnDelete? Thanks in advance.
Best Answer chosen by Rohan S
Khan AnasKhan Anas (Salesforce Developers) 
Hi Rohit,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Trigger:
trigger CountConOnAcc on Contact (after insert, after update, after delete) {

    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) {
        Handler_CountConOnAcc.countContact(Trigger.new);
    }

    if(Trigger.isDelete) {
        Handler_CountConOnAcc.countContact(Trigger.old);
    }
}

Handler Class:
public class Handler_CountConOnAcc {

    public static void countContact(List<Contact> contacts) {
        Set <Id> accountIds = new Set <Id>();
        List <Account> lstAccountsToUpdate = new List <Account>();

        for(Contact con:contacts){
            if(con.AccountId!=null){
            	accountIds.add(con.accountID);
            }
        }

        for(Account acc:[SELECT Id,Name,NumberOfContacts__c,(Select Id from Contacts) from Account where Id IN: accountIds]) {
            Account accObj = new Account ();
            accObj.Id = acc.Id;
            accObj.NumberOfContacts__c = acc.Contacts.size();
            lstAccountsToUpdate.add(accObj);
        }
    
        if(lstAccountsToUpdate.size()>0){
            UPDATE lstAccountsToUpdate;
        }
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas​​​​​​​

All Answers

Team NubesEliteTeam NubesElite
Hi Rohit,
In Trigger you should use operations
after insert,after update,after delete,after undelete
and trigger should be in Contact object.

Thank You
www.nubeselite.com

Developement | Training | Consulting

Please Mark this as solution if your problem resolved.

 
Rohan SRohan S
Hi Team NubesElite,
Appreciate your response, but I need someone to help me with the Apex class for this requirement.

Thanks
Team NubesEliteTeam NubesElite
Hi Rohit,
Please refer this code accordingly you can make changes
//Get the count of contacts in Accounts where Mailing country = USA(Accounts lookup into contacts) - ContactCountRollup
public class ContactTriggerHandler {
       public static void contactCountRollup() {
        set<id> accid = new set<id>();
        List<Contact> triggerOld = (List<Contact>)trigger.old;
        List<Contact> triggerNew = (List<Contact>)trigger.new;
        Map<Id,Contact> triggerOldMap = (Map<Id,Contact>)trigger.oldMap;
    for(Contact con : trigger.isdelete ? triggerOld : triggerNew){
        if(trigger.isupdate && triggerOldMap.get(con.id).MailingCountry != con.MailingCountry && 
           (triggerOldMap.get(con.Id).MailingCountry != null && triggerOldMap.get(con.Id).MailingCountry.EqualsIgnoreCase('USA')) 
           || (con.MailingCountry != null && con.MailingCountry.toLowerCase() == 'usa')) {
               accid.add(con.AccountId);
           } 
        else{
            accid.add(con.AccountId);
        }
        accid.add(con.AccountId);
    }
    if(accid.size()>0){
        List<account> acclist=[select id,(select id from contacts where MailingCountry='USA' )from account where id in:accid];
        for(Account acc : acclist){
            acc.Number_of_USA_Contacts__c = acc.contacts.size();
        }
            update acclist;
    }
}
}
Trigger
trigger ContactTrigger on Contact (after insert,after update,after delete,after undelete) {
        ContactTriggerHandler.contactCountRollup();
}



Thank You
www.nubeselite.com

Developement | Training | Consulting

Please Mark this as solution if your problem resolved.
 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Rohit,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Trigger:
trigger CountConOnAcc on Contact (after insert, after update, after delete) {

    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) {
        Handler_CountConOnAcc.countContact(Trigger.new);
    }

    if(Trigger.isDelete) {
        Handler_CountConOnAcc.countContact(Trigger.old);
    }
}

Handler Class:
public class Handler_CountConOnAcc {

    public static void countContact(List<Contact> contacts) {
        Set <Id> accountIds = new Set <Id>();
        List <Account> lstAccountsToUpdate = new List <Account>();

        for(Contact con:contacts){
            if(con.AccountId!=null){
            	accountIds.add(con.accountID);
            }
        }

        for(Account acc:[SELECT Id,Name,NumberOfContacts__c,(Select Id from Contacts) from Account where Id IN: accountIds]) {
            Account accObj = new Account ();
            accObj.Id = acc.Id;
            accObj.NumberOfContacts__c = acc.Contacts.size();
            lstAccountsToUpdate.add(accObj);
        }
    
        if(lstAccountsToUpdate.size()>0){
            UPDATE lstAccountsToUpdate;
        }
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas​​​​​​​
This was selected as the best answer