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
HARISH S 11HARISH S 11 

update the address field from account to contact

Hello I have been trying to update the contact record's address from account respective account record. But I have ended up in error saying

"Error: Compile Error: unexpected token: '<' at line 7 column 5". Below is the code, could somebody please help me?

trigger updatecontact1 on  Contact (after insert){
    List<contact> lstConUpdate = new List<Contact>();
    set<Id> sAccId = new set<Id>();
    for(Contact con: trigger.new){
        sAccId.add(con.AccountId);
    }
List<Account> lstAccount = [select id, Address_1__c, Address_2__c,City__c,Country__c(select id,Address_1__c, Address_2__c,City__c,Country__c from contacts) from account where id IN: sAccId];
    for(Account acc: lstAccount){
        for(Contact con: acc.contacts){
            con.Address_1__c = acc.Address_1__c;
            con.Address_2__c = acc.Address_2__c;
            con.City__c=acc.City__c;
            con.Country__c=acc.Country;
            lstConUpdate.add(con);
        }
    }
    if(lstConUpdate.size() > 0){
        update lstConUpdate;
    }   
}
Rahul Agarwal 45Rahul Agarwal 45
Try this - 
trigger updatecontact1 on  Contact (after insert){
    List<contact> lstConUpdate = new List<Contact>();
    set<Id> sAccId = new set<Id>();
    for(Contact con: trigger.new){
        sAccId.add(con.AccountId);
    }
List<Account> lstAccount = [select id, Address_1__c, Address_2__c,City__c,Country__c, (select id,Address_1__c, Address_2__c,City__c,Country__c from contacts) from account where id IN: sAccId];
    for(Account acc: lstAccount){
        for(Contact con: acc.contacts){
            con.Address_1__c = acc.Address_1__c;
            con.Address_2__c = acc.Address_2__c;
            con.City__c=acc.City__c;
            con.Country__c=acc.Country;
            lstConUpdate.add(con);
        }
    }
    if(lstConUpdate.size() > 0){
        update lstConUpdate;
    }   
}
HARISH S 11HARISH S 11
Thanks it worked, it had an another correcting at con.Country__c=acc.Country;

Which should be con.Country__c=acc.Country__c;

THanks again.
HARISH S 11HARISH S 11
Though the above program works very well. I have a doubt here. So am trying to insert a record all works fine. But if I want to update the exting records as well which is existing in the organization what needs to be done?

I tried adding after update keyword in the trigger which is throwing out an error like organization limit exceeded. COuld somebody please let me know what needs to be done?