+ Start a Discussion
Raj R.Raj R. 

How to check if picklist value exist in an Apex Trigger or Class?


I have a custom object which contains a field called Country, which is a text area field. If a certain criteria is met, a new Lead will be created using the data from that custom object. However, there is an issue because the Lead's Country field is a pick list and whenever the custom object's Country is not contained in the pick list or is a different variant of that country (i.e. United States vs United States of America). 

Within an apex trigger or class, how can i check if the custom object's country field value is a picklist value of the Lead standard object? If the custom object's country is a value contained in the Lead Country's pick list value then it inserts the Lead, ortherwise I can default the country or value to something else.

Below you will find a sample scenario
CustomObject obj = new CustomObject(FirstName='Test', LastName='Last', Country__c='United States');

//certain criteria is met
Lead newLead = new Lead();
newLead.FirstName = obj.FirstName;
newLead.LastName = obj.LastName;

       * this can cause an error because the Lead object's country picklist value for 'United States' is actually 'United States of America'
       * also, if 'United States' is not in the Lead's object Country Pick list value, then it causes an issue because there is absolutely no correct mapping
newLead.Country = obj.Country__c; 

insert newLead;

Best Answer chosen by Raj R.
David "w00t!" LiuDavid "w00t!" Liu
The above will return you all the possible picklist values. You can loop through the values or use a map to "search" it. 

This functionality is called dynamic Apex!