+ Start a Discussion
Robert Goldberg 9Robert Goldberg 9 

Updating A Trigger To Add Additional Restrictions

I have a working trigger that updates a lookup field from a zipcode object when the zipcode name = the listing zip code on the lead.  However, I need to add an additional restriction, where the metro__c field on the lead = the metro__c field on the zip code table, and I'm not sure how to do this.  How would I add this restriction?

The working trigger is below:

trigger UpdateListingZip on Lead (before insert, before update) {
    Set<String> ListingZips = new Set<String>();

    for( Lead l : trigger.new ) {
        if( l.listing_zip_code__c != null && l.LAG_Offered__c!=TRUE && l.DTA_Lead__c !=TRUE) {
            ListingZips.add( l.listing_zip_code__c );
                        
 }
    }            

        // Now we have a set of unique zipcodes we want to verify, time to look them up.
    // I plan to build a map of the "match field" -> "full reference object"

    Map<String, zip_codes__c> MatchZips = new Map<String, zip_codes__c>();

    for(zip_codes__c obj : [SELECT  Id,
                                           zipcode__c
                                            FROM    Zip_Codes__c
                                            WHERE     zipcode__c IN :ListingZips] ) {MatchZips.put( obj.zipcode__c, obj );
    }
    // We have all the reference data we need, last loop on the each lead

    for( Lead l : trigger.new ) {

        if( l.listing_zip_code__c != null ) { // there IS a countrylist entry to deal with... so...

            if( MatchZips.containsKey(l.listing_zip_code__c) ) { l.Zip_Code_Lookup__c = MatchZips.get(l.listing_zip_check__c).ID; }}
}
}
Best Answer chosen by Robert Goldberg 9
AshwaniAshwani
Another way you can create composite key for zip code + metro field. So you can compare both fields together as: MatchZips.put( obj.zipcode__c + obj.metro__c, obj );

All Answers

AshwaniAshwani
You can always use Sobject method to show the error message prevent insert, update of record.

 
leadRecord.getSObject('Status').addError('error message here');
It will show errro on Lead Status field and record won't update.

 
Robert Goldberg 9Robert Goldberg 9
That's not really an option - and how would I know that the two fields don't match?
AshwaniAshwani
Another way you can create composite key for zip code + metro field. So you can compare both fields together as: MatchZips.put( obj.zipcode__c + obj.metro__c, obj );
This was selected as the best answer
Robert Goldberg 9Robert Goldberg 9
That's exactly what I needed, Ashwani!  Thanks so much!