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
BryanTSCBryanTSC 

Trigger to populate Contact Fields

I have a custom object called Zip_Table that holds Zip Code specific information.  Is it possible to set a trigger on so that when a contact record is saved, it pulls the information related to their Zip Code into some custom fields on the Contact layout?

 

Any help is appreciated.  Thanks! 

JimRaeJimRae

Yes, this is very common functionality for a trigger.  Do it as a before insert, and the rest of the data can be added when the contact is saved.

To start, you will need to do something like this:

 

 

trigger Contact_ZipTrigger on Contact(before insert, before update){ Set <String> zips = new Set<String>(); for(Contact c : Trigger.new){ zips.add(c.zipcode);//add whatever the zipcode field is } Map<String,Zip_Code__C> zipMap = new Map<String,Zip_Code__c>();//get the set in one SOQL query include all of the custom fields you need, and match the zip value to the proper lookup from the custom object for(Zip_Code__c z :[select id,name, customfield__c from Zip_Code__c where name in :zips){ zipMap.put(z.Name, z); } //once you have the full map, you cycle through the contacts again and update as needed for(Contact newc : Trigger.new){ newc.customfield__c = zipMap.get(newc.zipcode).customfield__c; //repeat this for each custom field to update } }

 

 

 

BritishBoyinDCBritishBoyinDC
I recommend reading this post about someone doing the same thing, but with Contacts - really helped me understand the code constructs as well as getting it to actually work!