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
sourav046sourav046 

Trigger help

I want to write a trigger on Account so that when I edit the Phone field of an existing Account record ,the same Phone also auto populate in the Phone field of associated Contacts of that Account .

 

I have created a trigger but it shows exception .Please give me genuine way to avoid this exception or help me with code .

 

Here is my code

trigger updtPhone on Account (before update) {

for(Account acc:trigger.new){
List<contact> lst=new List<contact>();
Contact c=new Contact();
c=[SELECT Phone FROM Contact WHERE AccountId=:acc.id];
c.Phone=acc.Phone;
lst.add(c);
update acc;
}
}

 

Best Answer chosen by Admin (Salesforce Developers) 
PrakashbPrakashb

The code you have written does not handle bulk data.

 

Try the below code.

 

Map<Id,String> accmap = new Map<Id,String>();

For(Account a  :Trigger.New){

accmap.put(a.ID,a.Phone);

}

 

List<Contact> clist = new List<Contact>();

for(Contact c :  [select Id,Phone,AccountID from Contact where AccountID IN: accmap.Keyset()]){

c.Phone = accmap.get(c.AccountID);

clist.add(c);

}

 

Update clist;

All Answers

PrakashbPrakashb

The code you have written does not handle bulk data.

 

Try the below code.

 

Map<Id,String> accmap = new Map<Id,String>();

For(Account a  :Trigger.New){

accmap.put(a.ID,a.Phone);

}

 

List<Contact> clist = new List<Contact>();

for(Contact c :  [select Id,Phone,AccountID from Contact where AccountID IN: accmap.Keyset()]){

c.Phone = accmap.get(c.AccountID);

clist.add(c);

}

 

Update clist;

This was selected as the best answer
V AnandV Anand

If you want to write trigger for auto updation of contact phone filed  when you update the  account phone filed

then try this....

trigger updtPhone on Account (before update) {

  for(Account acc:trigger.new){
     contact c=[SELECT Phone FROM Contact WHERE AccountId=:acc.id];
     c.phone=acc.phone;
     update c;
  }
}

 Othewise let me know your exact trigger requirment.

sourav046sourav046

Hi vel123  !

 

Your code works fine if Account has one associated Contact only .Doesn't work for bulk Contact update and throws an exception .