You need to sign in to do that
Don't have an account?
TS21
In Trigger how to avoid for loop Inside for loop
I am creating a Trigger that whenever a Contact gets created or inserted the Account Name field will update to a specific account suppose name "xyz". Right now I have used For loop Inside a For Loop. Is there any way that I can avoid for loop inside for loop? Can I use Map here if yes How?
My current Code is :
My current Code is :
trigger AddConToAcc on Contact (before insert) { list<Account> listAcc = new List<Account>([SELECT Id, Name from Account where name = 'XYZ']); for(Contact con : Trigger.New){ for(Account acc : listAcc){ con.AccountId = acc.Id; } } }I tried to use a Map but its not working Code mentioned below :
trigger ContToAcc on Contact (before insert) { Set<Id> setAccId = New Set<Id>(); List<Account> acc = New List<Account>([SELECT ID FROM Account WHERE Name = 'XYZ']); for(Account acc1 : acc){ setAccId.add(acc1.Id); } Map<Id, Account> mapacc = new Map<Id, Account>([Select Id, Name FROM Account WHERE ID IN :setAccId]); for(Contact con : Trigger.New){ con.Account = mapacc.get(con.Account.Id); } }
Please use below code which has used Map in it. If before insert does not work then please try with after Insert. Please mark as best answer if helped.
Regards,
Ramakant
Thanks for your Reply!! However, above provided code doesn't work as listAcc which contains the list of account with name 'xyz' is not used anywhere.
Regards
Hope this will help.
Regards,
Ramakant
I believe if you are query with the specific account then it will return only one acocunt..if that is true then we don't have to add another loop to query an account.
Let me know if this helps you...
--
Thanks,
Prashant
1) http://amitsalesforce.blogspot.in/2016/09/collection-in-salesforce-example-using.html
Your code is very simple you can use code like below without For Map like below
If you Still want to use map only. Check above post and try to convert your code like below
Let us know if this will help you