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
John Neilan 18John Neilan 18 

Trigger Assistance for Related Record

Hi,

I have a lookup (Contact) field on the Account object. When a Contact is entered in this field, the trigger helper class below is meant to increment a field on the Contact (Referrals__c) by 1. It then also increments the Contact's associated Account field Referrals__c) by 1.  I don't think it is written in a way that is efficient. Is there a better way to accomplish this?
 
public class AccountUtility {
    public static void updateContactAccountReferredBy(List<Account> newAccountList){
        
		List<Contact> listContact = new List<Contact>();
        
        id oldReferredBy;

        for(Account account : newAccountList){
            Account oldAccount = (Account)Trigger.oldMap.get(account.Id);
            oldReferredBy = oldAccount.Referred_by__c;
            
            if(account.Referred_By__c != null && account.Referred_By__c != oldAccount.Referred_By__c){
                listContact = [SELECT Id,AccountId,Referrals__c
                               FROM Contact
                               WHERE Id =: account.Referred_By__c];
                for(Contact addReferral :listContact){
                    addReferral.Referrals__c += 1;
                    Account account2 = [SELECT Id, Referrals__c
                                      FROM Account
                                      WHERE Id =: addReferral.Id];
                    List<Contact> listContacts = [SELECT Id, Referrals__c
                                                 FROM Contact
                                                 WHERE AccountId =: account2.Id];
                    for(Contact contact2 :listContacts){
                        account2.Referrals__c += contact2.Referrals__c;
                    }
                    update account2;
                }
            update listContact;
            }
}

 
RituSharmaRituSharma
This requirement can be easily achieved using process builder and flow. So doing using declarative ways should be the best option.

With respect to the shared code, I would suggest:
1. Do not query inside loop
2. You have 3 layers of loop; reduce it
3. Don't perform DML in loop