You need to sign in to do that
Don't have an account?
John 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?
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; } }
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