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
Brian GazaBrian Gaza 

Update Account Fields from Lookup on Related Account

I use Apex about once a year or so, so I still struggle every time...

Trying to update Billing Address fields on a Person Account based on a Lookup field that refers to another account record.

Basically, I have a lookup field called Employer and I want to pull in the address from the Employer account into the related person account. I've tried searching for some code to start with, but haven't had any luck. 

Any help is appreciated!
Brian
GauravGargGauravGarg

Hi Brian,

You need to query on Account based on Employer account Id and then set the Address information field on current account fields.

Please let me know if you need help on this. 
 

Thanks,

Gaurav
Email: gauravgarg.nmims@gmail.com
 

Head In CloudHead In Cloud
Hi Brian,

You can use the below trigger to achieve this:
 
trigger testTrigger on account (before insert, before update){
    map<string, account>mapOfEmployers = new map<string, account>();
    set<string> setOfIds =new set<string>();
    for(account acc : trigger.new){
        if(acc.Employer__c != null){
            setOfIds.add(acc.Employer__c);
        }
    }
    for(Account acc : [select id, billingstreet, billingcity, billingcountry, billingpostalcode, billingstate from account where id in: setofIds]){
        mapOfEmployers.put(acc.id, acc);
    }

    for(account a : trigger.new){
        if(a.Employer__c != null && mapOfEmployers != null && mapOfEmployers.containsKey(a.Employer__c)){
            a.billingStreet = mapOfEmployers.get(a.Employer__c).billingStreet;
            a.billingState = mapOfEmployers.get(a.Employer__c).billingState;
            a.billingCity = mapOfEmployers.get(a.Employer__c).billingCity;
            a.billingCountry = mapOfEmployers.get(a.Employer__c).BillingCountry;
            a.billingpostalCode = mapOfEmployers.get(a.Employer__c).billingpostalCode;
        }
    }
}

Please mark this answer as solved if it helps you.
Brian GazaBrian Gaza
I've attempted to use the code you provided, Head In Cloud, but I've run into an issue in that we use Person Accounts... should the trigger run on Account or Contact? Employer__c is a custom Lookup field related to Account, but then Employer__pc also exists...
Head In CloudHead In Cloud
Your trigger should be working on Account. If you are able to get Employer__c in a query, then you should use Employer__c in the trigger. But if you see the api name as Employer__pc, then you should use that.