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
KPDKPD 

Update trigger

Hello can someone help me on below trigger.
I have a scenario that If account is updating for phone number then all associated contacts phone number should update with same number. 
I wrote the trigger as below.It doesnt throw any errors but the phone number doesnt gets updated.

trigger phupdate on account (after update) 
{
List<contact> ctlist =new list<contact>();
List<Id> ids = new List<Id>();
for(account ac: trigger.new)
{
ids.add(ac.Id);
}
Map<Id, contact> contactMap = new Map<Id, contact>([Select Id, Phone From contact Where Id In :ids]);
for(account ac: trigger.new)
{
contact c = contactMap.get(ac.Id);
if(c != null)
{
ac.Phone= c.Phone;
ctlist.add(c);
}
}
update ctlist;
}
 
IshwaryaIshwarya
Hi,
The Query you have given is not fetching any records.
Please try below code.


trigger phupdate on account (after update) 
{
List<contact> ctlist =new list<contact>();
List<Id> accids = new List<Id>();
for(account ac: trigger.new)
{
accids.add(ac.Id);
}
    
List<contact> conList = new List<contact>();
    conList = [Select Id, Phone From contact Where account.Id In :accids];
    for(account ac: trigger.new)
    {
        for(contact c:conList)
        {
            c.Phone = ac.phone;
            
        }
    }

update conList;
}
 
sandip bijlwansandip bijlwan
please add if condition to check if the contact is related to particular account.

for(account ac: trigger.new)
    {
        for(contact c:conList)
        {    
            if(acc.id == c.AccountID){
                
                c.Phone = ac.phone;
            }
            
            
        }
    }

this would solve your problem
Mahesh K 22Mahesh K 22
HI PGMD
Try this trigger
TRIGGER:

trigger phonefiledupdate on Account (after update) {
 set<id> newset = new set<id>();
    for(account a : trigger.new){
        if(a.phone !=trigger.oldmap.get(a.Id).phone){
        newset.add(a.id);
    }
    }
    list<contact> cons = new list<contact>();
    list<account> acclst = [select id,name,phone,(select id,lastname,phone from contacts)
                         from account where id IN : newset];
    for(account ac : acclst){
        for(contact c : ac.contacts){
            c.phone = ac.phone;
            cons.add(c);
        }
    }
    update cons;
}
KPDKPD
Thank you all.
I am new to apex coding so trying to learn.