Question

I'm trying to find a way to automatically copy from one field to another field in Salesforce Contacts if at all possible please. (i.e. I have one field called "Contact: Mailing Zip/Postal Code" that I'm trying to automatically copy to another field called "Postcode_Lookup_c" .)

The purpose behind it is to automatically copy a field with a contact’s postcode/ZIP code to a formula lookup field, that references a custom object I've created called Postcode_Lookup__c. This basically links certain field relationships together, to which I've linked a list of local councils & regions in the state.

The idea being that a contact will be auto-populated with their relevant local council and region of the state, based on their mailing address postcode.

Thanks so much for your help, Joe :-)

Was it helpful?

Solution

For anyone else that's ever trying to do the same thing, here's the code that ended up accomplishing the task...

trigger Postcode_Copy on Contact(before insert, before update) {

  Set < String > MailingPostalCodes = new Set < String > ();
  Map < String, Postcode_Lookup__c > postCode_Postal_map = new Map < String, Postcode_Lookup__c > ();

  for (Contact a: Trigger.new) {
    if (a.MailingPostalCode != null && a.MailingPostalCode.trim() != '')
      MailingPostalCodes.add(a.MailingPostalCode);
  }

  for (Postcode_Lookup__c postRec: [Select ID, Name from Postcode_Lookup__c where Name in: MailingPostalCodes]) {
    postCode_Postal_map.put(postRec.Name, postRec);
  }
  if (postCode_Postal_map.size() > 0) {
    for (Contact con: Trigger.new) {
      if (con.MailingPostalCode != null && con.MailingPostalCode.trim() != '') {
        if (postCode_Postal_map.containsKey(con.MailingPostalCode)) {
          con.Postcode_Lookup__c = postCode_Postal_map.get(con.MailingPostalCode).id;
        }
      }
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top