Write a trigger to Auto populate Contact fields when account lookup will be selected

By | December 13, 2019

Hi, here we going to learn about write a trigger on before insert the record then auto populate the contact fields based on account fields when account lookup will be selected

Apex Class:

public class AccToConCityAutopopUpdate{
    public static void FieldPopulate(list<account>acc){
        map<id,account> accmap = new map<id,account>();
        for(account ac:acc){
            accmap.put(ac.id,ac);
        }
        list<contact> con=[select id,Lastname,MailingCity,account.BillingCity from contact where id=:accmap.keyset()];//add fields here
        for(contact c:con){
            c.MailingCity=accmap.get(c.accountid).BillingCity;//add fields for your requirement
            con.add(c);
        }
        update con;
    }
}

Trigger:

trigger AccountToContactCityUpdate on Account (before insert,before update) {
    AccToConCityAutopopUpdate.FieldPopulate(trigger.new);
}

Output:

Share this...
Share on Facebook
Facebook
Email this to someone
email

Leave a Reply

Your email address will not be published. Required fields are marked *