You need to sign in to do that
Don't have an account?
sourav046
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; } }
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
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;
If you want to write trigger for auto updation of contact phone filed when you update the account phone filed
then try this....
Othewise let me know your exact trigger requirment.
Hi vel123 !
Your code works fine if Account has one associated Contact only .Doesn't work for bulk Contact update and throws an exception .