I'm am having a ridiculous time finding basic Trigger examples (background: no official training, have books, have experience elsewhere, figuring this out on my own).
I am trying to write an insanely simple trigger that does a Lookup. CountryList is on Lead, I have made a custom object CountryLists. I want to verify if CountryList from Lead exists in the field "Country" in object CountryLists.
I have tried several iterations of code and keep getting mixed up on my initial Trigger.new call versus looping through either the Custom Object or the Leads to find if it yields a null or not. Literally, IF NOT NULL, then (do things to the Lead). That's it.
Does someone have an example or source of examples? Googling such things is a crap-shoot anymore.
Thanks so much.
ADDED: EXPANDED REASONING
One of the things I will do if NULL is found is put a value "(Undefined)" into field REGION__C on the Lead.
As well, if it is NOT NULL, I will be populating REGION__C on the Lead with an equivelent Region variable from the matching CountryLists entry.
Effectively.... United States of America will get a Region__c _ of "North America", as an example. Currently this is done via (many) workflows (for over 200 countries, INCLUDING all their misspelled/alternate texts). Our many lead sources are NOT consistent of course. Having this in a custom object makes sense. I'm just missing the actually "does Lead.Countrylist_c exist inside CountryLists.Country_c? IF SO, do this, IF NOT, do that." :-/
SOLUTION CREATED FROM HELP GIVEN BELOW:
trigger Country_List_Lookup_LEADS on Lead (before insert,before update) {
Set<String> countryNames = new Set<String>();
for( Lead l : trigger.new ) {
if( l.CountryList__c != null) {
countryNames.add( l.CountryList__c );
}
}
// Now we have a set of unique country names we want to verify, time to look them up.
// I plan to build a map of the "match field" -> "full reference object"
Map<String, Country_List_Reference__c> validCountries = new Map<String, Country_List_Reference__c>();
for( Country_List_Reference__c obj : [SELECT Id,
MTI_Region__c,
Country__c
FROM Country_List_Reference__c
WHERE Country__c IN :countryNames] ) {
validCountries.put( obj.Country__c, obj );
}
// We have all the reference data we need, last loop on the each lead
for( Lead l : trigger.new ) {
if( l.CountryList__c != null ) { // there IS a countrylist entry to deal with... so...
if( validCountries.containsKey(l.CountryList__c) ) { // found it, do your stuff
l.Region__c = validCountries.get(l.CountryList__c).MTI_Region__c;
} else { // do stuff when NOT found
l.Region__c = '{UNKNOWN COUNTRY LIST ENTRY)';
}
} else { // there IS NOT a countrylist entry to deal with...
l.Region__c = '(COUNTRY LIST IS EMPTY)';
}
}
}
I will be expanding the IF...ELSE section at the bottom, but this got the job done. Special thanks to @EyeScream and those who offered their input as well. ;-)