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
Scott Blase 9Scott Blase 9 

New to Apex Triggers

I am new to apex classes and triggers....what I need to create is a trigger that will update an account field from another account field.   I want the Billing Zip/Postal Code to update a lookup field named Zip Territory Lookup.  This will ultimately drive which territory each account falls under.

Any ideas?
GauravGargGauravGarg
Hi Scott,
  • You need to create mapping for Zip/Postal code with Lookup Object i.e. exact same mapping so that Apex would identify the unique record. 
  • create trigger on before Insert, Before Update
  • Before Insert:
    • Check ZIP / Postal code isn't blank. 
  • Before Update:
    • Check ZIP / Postal Code is not same as Old Map i.e. previous value or blank. 
  • Trigger Account_AT on Account (before Insert, before Update)
    {
    	List<String> postalCodes = new List<String>();
    	set<id> removedPostalCodes = new set<Id>();
    	for(Account acc : Trigger.new)
    	{
    		if(trigger.isInsert && acc.BillingPostalCode != '')
    			postalCodes.add(acc.BillingPostalCode);
    		else if(trigger.isUpdate && (acc.BillingPostalCode != OldMap.get(acc.id).BillingPostalCode))
    			postalCodes.add(acc.BillingPostalCode);
    		else if(trigger.isUpdate && (acc.BillingPostalCode != OldMap.get(acc.id).BillingPostalCode && acc.BillingPostalCode == ''))
    			removedPostalCodes.add(acc.id);
    	}
    	
    	Map<String, ZipCodeObject__c> zipRecords = new Map<String, ZipCodeObject__c>();
    	for(ZipCodeObject__c zip : [SELECT Id, Name FROM ZipCodeObject__c WHERE Name IN :postalCodes])
    	{
    		zipRecords.put(zip.Name, zip);
    	}
    	
    	for(Account acc : trigger.New)
    	{
    		if(acc.BillingPostalCode != '' && zipRecords != null && zipRecords.size() > 0 && zipRecords.containsKey(acc.BillingPostalCode))
    		{
    			acc.ZipCodeField__c = zipRecords.get(acc.BillingPostalCode).id;
    		}
    		else if(acc.BillingPostalCode == '' && removedPostalCodes.contains(acc.BillingPostalCode)) // if Zip Code is remove, delink the ZIP lookup.
    		{
    			acc.ZipCodeField__c = null;
    		}
    	}
    }

Hope this helps !!!

Thanks,

Gaurav
skype: gaurav62990