You need to sign in to do that
Don't have an account?
sonali verma
Optimize apex code using Map
Hi
I have a requirement.When we update Account record, the related Description field of contact object should get updated automatically.
I am able to achieve the requirement but I want to know whether we can use Map to optimize the code further.
Pls help me.
Thanks
sonali
I have a requirement.When we update Account record, the related Description field of contact object should get updated automatically.
I am able to achieve the requirement but I want to know whether we can use Map to optimize the code further.
Pls help me.
public class Account_ContactDescription { public static void Update_Description(Set<Id> accountIds) { list<Account> accountsWithContacts =[select Id,Name, (select Id,FirstName,LastName from Contacts) from Account where Id IN : accountIds]; list<Contact> contactsToUpdate=new list<Contact>(); for(Account a:accountsWithContacts) //loop through all queries { for(Contact convals:a.Contacts) { convals.Description=convals.FirstName+' '+convals.LastName; contactsToUpdate.add(convals); } } update contactsToUpdate; } } trigger trg_Description on Account (before Update) { Account_ContactDescription c=new Account_ContactDescription(); Map<Id,Account> amap = new Map<Id,Account>([select Id from Account]); Set<Id> accountIds = amap.KeySet(); c.Update_Description(accountIds); }
Thanks
sonali
You can achieve this functionality with Process Builder too. However, if you want to accomplish this using trigger you can use below mentioned code. I have optimized your code a bit:
All Answers
You can achieve this functionality with Process Builder too. However, if you want to accomplish this using trigger you can use below mentioned code. I have optimized your code a bit:
I ran ur code and it works.
I checked the code with before Udpate event and it works.
Can u pls clarify whether "before Update" or "after Update" is an better option in this case?
Thanks
sonali verma