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
vikas  malikvikas malik 

Lead trigger to query Zip Code custom object not working

I'm trying to implement lead assignment based on zip codes, and I'm running into an error with the code. I set up a Zip Code custom object, Zip_Code__c, where the name is the zipcode. Both the custom object and the Lead object have a custom text field, CA_Territory__c (this is for California zip codes only). When the zip code on a lead is entered or edited, I want to pull the CA Territory value from the custom object into the lead field. This is the code:

trigger CATerritory on Lead (before insert, before update) { 
//get the first five digits of the PostalCode from the lead 
set<string> left5zips = new set<string>(); 
for (lead l: trigger.New) if (l.postalcode !=null) left5zips.add(l.postalcode.substring(0,5));

//if no zip listed on the lead 
if(left5zips.isEmpty()) lead.ca_territory__c='None'; 

//query the zip_code object to get the zipcode (Name) and zone from the zip code object 
map<string,string> zmap=new map<string,string>(); 
  for(Zip_Code__c z :
     [Select name, ca_territory__c from Zip_Code__c WHERE name IN :left5zips])
zmap.put (z.name, z.ca_territory__c);

for(lead l:trigger.new){ 
if(zmap.containskey(l.left5zips)) 
     l.ca_territory__c=zmap.get(l.left5zips); 

}
The error I am getting is 'Compile Error: Expression cannot be assigned at line -1 column -1'. This is my first attempt at a trigger, and it is based on other people's code, so I don't really know how to troubleshoot. Any ideas? Thanks!
Best Answer chosen by vikas malik
Gaurav NirwalGaurav Nirwal
I think the issue is with the way I defined left5zips as a Lead field in the last for statement. I had this posted on another forum as well, and I found this solution, which works:

trigger CATerritory on Lead (before insert, before update) { 
    set<string> left5zips = new set<string>(); 
    for (lead l: trigger.New) {
        if (l.postalcode != null) {
            left5zips.add(l.postalcode.substring(0,5));
        }
    }

    //query the zip_code object to get the zipcode (Name) and zone from the zip code object 
    map<string,string> territoryMap=new map<string,string>(); 
    for(Zip_Code__c z : [Select name, ca_territory__c from Zip_Code__c WHERE name IN :left5zips]) {
        territoryMap.put (z.name, z.ca_territory__c);
    }

    for (lead l: trigger.new) {
        if(l.postalcode != null) {
            String territory = territoryMap.get(l.postalcode.substring(0,5));
            if (territory != null) {
                l.ca_territory__c = territory;
            }

        }
        if (l.ca_territory__c == null ) {
            l.ca_territory__c = 'None';
        }
    }
}