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
thomas rosickythomas rosicky 

How could the use of Lists, Sets, or Maps help avoid governor limit exceptions in the following code? Please give a detailed description which would be helpful.

for (Account a : trigger.new){
for (Contact c : [select id,otherphone from contact where accountid = :a.id]) {
c.OtherPhone= a.Phone; update c;
}
ManojjenaManojjena
Hi Thomas,

PLease check below code which you can understand by the help of comments .
 
In below code you have two issue in code which will hit limit ,DML inside for loop ,and SOQL insde for loop .
for (Account a : trigger.new){
for (Contact c : [select id,otherphone from contact where accountid = :a.id]) {
c.OtherPhone= a.Phone; 
update c;
}

//List to avoid DML inside for loop
List conListToupdate=new List();
//Query from account with trigger.new list which will return only contact related to manipulated account 
for(Contact con : [SELECT id,AccountId,OtherPhone FROM Contact WHERE AccountId IN :Trigger.new ]){
  //Assign contact other phone field from related account phone 
  //To get the phone from related account we have passed the contcat related accountid which will refer to 
  //the account record in new map with .dot notation we can get value from the account .
  con.OtherPhone=Trigger.newMap.get(con.AccountId).Phone;
  //Adding each account to list 
  conListToupdate.add(con);
}
try{
//update list of account to avoid DML limit 
  update conListToupdate;
}catch(DMLException de ){
  System.debug(de);
}

Let me know if it help !!
Thanks 
Manoj
Amit Chaudhary 8Amit Chaudhary 8
Hi thomas rosicky,

I found two issue in your code 
1) DML inside loop
2) SOQL inside Loop

for (Account a : trigger.new){
for (Contact c : [select id,otherphone from contact where accountid = :a.id]) {
c.OtherPhone= a.Phone; update c;
}

Please try below code :-
Set setAccID = new Set();
for (Account a : trigger.new)
{
	setAccID.add(a.id)
}

List listAccount = [select id,name,Phone ,(select id, firstName,LastName ,OtherPhone from contacts) from Account where id in:setAccID];

List listOfContToUpdate = new List();
for(Account acc :listAccount)
{
	List lisCont = acc.contacts;
	for (Contact cont : lisCont ) 
	{
		cont.OtherPhone= acc.Phone; 
		listOfContToUpdate.add(cont);
	}	
}

if(listOfContToUpdate.size() > 0)
{
	update listOfContToUpdate;
}

Always Salesforce best Practice 
http://amitsalesforce.blogspot.in/2015/06/trigger-best-practices-sample-trigger.html

Please let us know if this will help you

Thanks
Amit Chaudhary