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
Rupesh BRupesh B 

Trigger on contact to update Account address to contacts address when created a new contact

I am having some errors in the below code for the trigger to update contact address with Account Address using apex controller

public class ContactUpdateAccountAddress {
    public static void updatecontacts(List<Contact> contactlist){
        updateAddressToContacts(contactlist);
        
    }
    public static void updateAddressToContacts(List<Contact> contactlist){
        set<id> accIds = new set<id>();
        list<account> updAccaddr = new list<account>();
        for(contact con : contactlist){
            accIds.add(con.accountid);
        }
        system.debug('###'+accIds);
        list<account> acclist = [select id,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry,(select id,MailingStreet,MailingCity, MailingState,MailingPostalCode,MailingCountry from contacts) from account where id in : accIds];
        for(Account acc : updAccaddr) {
        for(Contact con : contactlist){
           con.MailingStreet =  acc.BillingStreet ;
            contactlist.add(con);
        }
            }
        update contactlist;
    }

trigger ContactUpdateAccountAddressTrigger on Contact (before insert, after update, after delete) {
    if(trigger.isInsert && trigger.isbefore){
        ContactUpdateAccountAddress.updatecontacts(trigger.new);
    }
Best Answer chosen by Rupesh B
Meghna Vijay 7Meghna Vijay 7
Hi Rupesh, 
There is no need to fire a DML operation in before Trigger as the record hasn't been saved to the database. So remove update contactlist: 
First way:-
// There is no need to do an inner query at all 
list<account> acclist = [select id,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry from account where id in : accIds];
for(Account acc : updAccaddr) { // It should loop on accList not updAccaddr 
// Right code
for(Contact con : contactlist){
       for(Account acc : acclist){        
           if(con.AccountId == acc.Id) {
              con.MailingStreet = acc.BillingStreet ;  
              break; 
          }                     
        }
     }

Second Way:-
Map<Id, Account> accMap = new Map<Id, Account>([select id,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry from account where id in : accIds]);
for(Contact con : contactlist){
  for(Account acc : accMap.get(con.AccountId)){
    con.MailingStreet = acc.BillingStreet ;
  } 
} 
Hope it helps, if it does mark it as solved.
Thanks
 

All Answers

Meghna Vijay 7Meghna Vijay 7
Hi Rupesh, 
There is no need to fire a DML operation in before Trigger as the record hasn't been saved to the database. So remove update contactlist: 
First way:-
// There is no need to do an inner query at all 
list<account> acclist = [select id,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry from account where id in : accIds];
for(Account acc : updAccaddr) { // It should loop on accList not updAccaddr 
// Right code
for(Contact con : contactlist){
       for(Account acc : acclist){        
           if(con.AccountId == acc.Id) {
              con.MailingStreet = acc.BillingStreet ;  
              break; 
          }                     
        }
     }

Second Way:-
Map<Id, Account> accMap = new Map<Id, Account>([select id,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry from account where id in : accIds]);
for(Contact con : contactlist){
  for(Account acc : accMap.get(con.AccountId)){
    con.MailingStreet = acc.BillingStreet ;
  } 
} 
Hope it helps, if it does mark it as solved.
Thanks
 
This was selected as the best answer
SFDC Prime SquadSFDC Prime Squad
Hi Rupesh,

For your scenario, you need to update contact fields in contact trigger. So all your trigger contexts should be "Before" triggers.

Also, you do not need delete triggers, as in when contact is deleted, there is no action required.

Along with this, in before triggers, the trigger context variables itself modifies the values assigned and hence there is no need of explicit update.

Updated code:
public class ContactUpdateAccountAddress {
    public static void updatecontacts(List<Contact> contactlist){
        updateAddressToContacts(contactlist);
        
    }
    public static void updateAddressToContacts(List<Contact> contactlist){
        set<id> accIds = new set<id>();
        for(contact con : contactlist){
            if(con.accountid != null){
                accIds.add(con.accountid);
            }
        }
        system.debug('###'+accIds);
        map<Id,account> accMap = new map<Id,Account>([select id,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry from account where id in : accIds]);
        
        for(Contact con : contactlist){
            if(!accMap.isEmpty() && accMap.containsKey(con.AccountId)){
                con.MailingStreet =  accMap.get(con.AccountId).BillingStreet ;
           }
        }
    }

trigger ContactUpdateAccountAddressTrigger on Contact (before insert, before update) {
    if((trigger.isInsert || trigger.isUpdate) && trigger.isBefore){
        ContactUpdateAccountAddress.updatecontacts(trigger.new);
    }
DevADSDevADS
Update your class with below code - 
public class ContactUpdateAccountAddress {
    public static void updatecontacts(List<Contact> contactlist){
        updateAddressToContacts(contactlist);
        
    }
    public static void updateAddressToContacts(List<Contact> contactlist){
        
        Map<Id,List<Contact>> accConMap = new Map<Id,List<Contact>>();
        list<contact> updatedConList = new list<contact>();
        
        for(contact con : contactlist){
            if(accConMap.containsKey(con.accountid))
            accConMap.get(con.accountid).add(con);
            accConMap.put(con.accountid, new List<Contact>{con});
        }
   
        list<account> acclist = [select id,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry from account where id in : accConMap.keySet()];
        for(Account acc : acclist) {
            for(Contact con : accConMap.get(acc.id)){
                system.debug(acc.BillingStreet);
                con.MailingStreet =  acc.BillingStreet ;
            }
        }
    }
}

Happy Coding!
Rupesh BRupesh B
Thanks a lot, @Meghna Vijay 7 & @SFDC Prime Squad.