+ Start a Discussion
Kiru535Kiru535 

Populating Account address in contact

My Requirement was during upon selected an account on contact while creating new contact or update contact.... Account address to be populated on contact automatically. During insert the trigger is working properly but an update it is not working. Please suggest me what i need to change in below code.

trigger PopulateAccountAddress on Contact (before insert,before update)
{
  Map<id,Account> accaddress = new Map<id,Account>();
  List<Account> acclist = [Select id,BillingCity,BillingCountry,BillingPostalCode,BillingState,BillingStreet from Account];
  for(Account addaddress : acclist)
  {
    accaddress.put(addaddress.id,addaddress);
  }
  System.debug ('*****accaddress Map*****' + accaddress);
  for(Id conaddress:accaddress.keyset())
  {
      System.debug('Address ids' + conaddress);
        
         Contact c = new Contact();
        System.debug('!!!!!conaddress!!!!!!' + conaddress);
        c.MailingCity = accaddress.get(conaddress).BillingCity;
        System.debug('$$$$ MailingCity $$$$$' + c.MailingCity);
        c.MailingCountry = accaddress.get(conaddress).BillingCountry;
        c.MailingPostalCode= accaddress.get(conaddress).BillingPostalCode;
        c.MailingState = accaddress.get(conaddress).BillingState;
        c.MailingStreet= accaddress.get(conaddress).BillingStreet;
       
          
    }   
   }
dev_sfdc1dev_sfdc1
Hi,
Your requirement for update should be from account to contact or contact to account or else both object.. Which one?
Nirmal ChristopherNirmal Christopher
try something like this trigger PopulateAccountAddress on Contact (before insert,before update)
{
set<id>contactidset=new set<id>();
for(contact c : trigger.new){
contactidset.add(c.id);
}
list<contact>newcon=[select id,Accountid,name from contact where id IN:contactidset];
List<Account>relatedacc=new list<account>();

for(integer i=0;i<newcon.size();i++){
relatedacc=[select id,ShippingStreet from account where id=:newcon[i].accountid];
system.debug('++++++++++++++++++++++++'+relatedacc);
}
for(contact coo:newcon){
for(integer i=0;i<relatedacc.size();i++)
   coo.MailingStreet = relatedacc[0].ShippingStreet ;
   system.debug('+++++++++++MailingStreet +++++++++++++'+ coo.MailingStreet );

}

      }
Kiru535Kiru535
I tried but this code  also not working incase of update.............
Nirmal ChristopherNirmal Christopher
It printed in debug logs while updating. let me check and get back to you.
Kiru535Kiru535
Hi Nirmal,

Any luck on this...................