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
Heena.Heena. 

write a trigger to update a field (let it be city) in all related opportunities when same field(city) is updated in account

Narender Singh(Nads)Narender Singh(Nads)
Hi,
Let us say you have a custom field on your Account object named AccCity__c and a custom field on Opportunity object name OppCity__c.
Then your trigger will look like this:
trigger UpdateCity on Account (after update) {
    
    Opportunity[] OppListToUpdate=new Opportunity[]{};
    map<id,account> Accmap=new map<id,account>();
    for(Account a:trigger.new){
        if(a.AccCity__c !=trigger.oldmap.get(a.id).AccCity__c)
            Accmap.put(a.id,a);
    }
    
    if(!Accmap.isEmpty()){
        Set<id> AccIDs=Accmap.keyset();
        Opportunity[] Opplist=[Select id, AccountId,OppCity__c from Opportunity where Id in :AccIDs];
        
        if(Opplist.size()>0){
            for(Opportunity o: Opplist ){
                o.OppCity__c=Accmap.get(o.accountId).AccCity__c;
                OppListToUpdate.add(o);
            }
        }
    }
    
    if(OppListToUpdate.size()>0){
        update OppListToUpdate;
    }
}
Note: There may be few typos here and there since its not compiled.

If my answer helps you, please mark it as the best answer.
Let me know if you have any queries.

Regards,
Narender
 
richa chaturvediricha chaturvedi
just add List< Opportunity> Opplist=[Select id, AccountId,OppCity__c from Opportunity where Id in :AccIDs]; in line 12
Jatin Gupta 41Jatin Gupta 41
This Program will only work when you use AccountId in place of Id in SOQL for opportunity.