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
Jeremy FrinkJeremy Frink 

Create Apex Trigger to update checkbox if zip code includes

I have several hundred zip codes that I would like to check and if the zip code field contains any of these zip codes I would like to have the trigger update a checkbox.

If zip code includes xxxxx or xxxxx, then check box "Urban" "Rural" or "Suburban" 

I can't do this with a formula field as it exceeds the length restrictions. 

Any assistance would be appreciated.
Best Answer chosen by Jeremy Frink
SarvaniSarvani
Hi Jeremy,

I hope this sample code helps you to deign your trigger on your Sobject.
trigger ZipCheck on Account (before insert,before update) {
// input your zipcodes list based on urban,rural and suburban lists like below.
    list<String> ZipcodesUrban= new list<String>{'12345','67891'};
    list<String> ZipcodesRural= new list<string>{'45678','34521'};
    list<Account> Acclist= new list<Account>();
// Check if the new records zip code field is null and add records to your list.    
For(Account Acc: Trigger.new){
        if(Acc.zip_code__c!=NULL){
            Acclist.add(Acc);
        }
        
    }
// in case if you have any reocrds with zipcodes do below
    if(Acclist.size()>0){
        for(Account A:Acclist){
// condition check of new zip code with existing zipcodes in the lists (Urban,Rural and Suburban) and update checkbox accordingly.
            for(integer i=0;i<ZipcodesUrban.size();i++){
               if((A.Zip_Code__c)==ZipcodesUrban.get(i)) {
                    A.Urban__c=true;
               }              
            }
            for(Integer i=0;i<ZipCodesRural.size();i++){
               if((A.Zip_Code__c)==ZipcodesRural.get(i)) {
                    A.Rural__c=true;
               }  
            }
        }
    }
}

Hope this helps! Please mark as best solution if it helps you.

Thanks