+ Start a Discussion
Tomeka WrayTomeka Wray 

Picklist Field Validation and Apex Code

I have a Apex class that automatically creates a lead when certain conditions apply to case from another Org. However, the state field is a picklist and somestimes the field values from the sending org are not always in the receiving orgs picklist. How can I validate that the State received is actually in the picklist. 

My initial thought was to create a string array with all of the valid values and compare the state against that, but if the picklist changes, then my code will not be accurate. Any suggestions would be much appreciated. 
Best Answer chosen by Tomeka Wray
Tavva Sai KrishnaTavva Sai Krishna
Hi Tomeka,

I understood that in the options map you are able to get all the picklist values present in the stateCode.(All countries). 
Your query is how to limit it for 'US'.

I got this reference to check the ISO-3166 standard state/country codes.
https://help.salesforce.com/HTViewHelpDoc?id=admin_state_country_picklists_standard_countries.htm&language=en_US (https://help.salesforce.com/HTViewHelpDoc?id=admin_state_country_picklists_standard_countries.htm&language=en_US" target="_blank
with this i made a check in the for loop to the picklist values to the options map . see updated code below.
public static List<Lead> scrubStates (List<Lead> LeadCases){
        List <Lead> validStates = new List<Lead>();
        
        //Gets the value of the valid states
  		List<Schema.PicklistEntry>  fieldResult = Lead.statecode.getDescribe().getPicklistValues();
        system.debug('States = ' + fieldResult);
        
        Map<string,string> options = new Map<string,string>();
		for( Schema.PicklistEntry f : fieldResult )
   			{   
                // Added condition to check the 'US' Country.
				if(f == 'US'){
					options.put(f.getLabel(),f.getLabel());
					system.debug('State =' + f.getLabel());
				}
			}
        for (Lead l : LeadCases){
		
            //Validates case to ensures that the state is valid 
            if(options.get(l.State) !=  null){
         		validStates.add(l);
				}
        }
        system.debug('Before State Scrub = ' + LeadCases.size());
        system.debug('After State Scrub = ' + validStates.size());
        return validStates;
    }
Let me know if it helps or you want any other.
Please mark this as best answer to help others in future.

Thanks and Regards,
Sai Krishna Tavva.
 

All Answers

Tavva Sai KrishnaTavva Sai Krishna
Hi Tomeka,

Edit the picklist field, set the check box labeled  Strictly enforce picklist value  true to prevent the values otherthan the picklist values. see
below screenshot for more info.

1. Edit the picklist field . (Eg: here in this screenshot Primary is the custom field type picklist.)

User-added image
2. check the checkbox as highlighted in the below screenshot.
User-added image

Then it only checks the picklist values,other than the picklistvalues will not be considered.

Please let me know if you have any queries. Also mark it as best answer if this answers to your question as it may helpful to others.

Thanks and Regards,
Sai Krishna Tavva.
Tomeka WrayTomeka Wray
Thank you for your response Sai. However, that is not my issue. The picklist is being enforced, I need to know how to check my field value using Apex before I try to insert the object.
 
ublic class createS2SLead {
   
    public static void createLead (){
       
        Integer counter = 0;
        List <Case> updatedCases = [Select Id, Subject, CaseNumber, Org_Name__c, 
                                Contact_Name_Copy__c, 
                                Org_Street__c,
                                Org_City__c,
                                Org_State__c,
                                Org_Country__c,
                                Copy_Contact_Email__c,
                                Fee_Based_Service__c,
                                Lead_ID__c,
                                ITA_Ref_Case_Number__c,
                                Case_Close_Date__c
                              
        						From Case WHERE Lead_ID__c = null AND Org_State__c != null AND Org_Country__c = 'United States'];
 
     
        Assignmentrule AR = new Assignmentrule();
        AR = [SELECT id, name FROM AssignmentRule WHERE name = 'DOC Lead Assignment'];
        system.debug('Assignment Rule:'+ AR.Name + 'ID =' + AR.Id);
    	List<Lead> caseLead = new List<Lead>();
        Database.DMLOptions dmo = new Database.DMLOptions();
        dmo.assignmentRuleHeader.assignmentruleid = AR.ID;
  		//dmo.assignmentRuleHeader.useDefaultRule= true;
     	//Loops Through all of the new Cases and Creates
    	//a corresponding lead
    	for (Case c : updatedCases){

        	if (c.Org_Name__c != null && c.Contact_Name_Copy__c != null){
        		caseLead.add(new Lead(Company = c.Org_Name__c,
                              Street = c.Org_Street__c,
                              City = c.Org_City__c,

//This is where I need to check if c.Org_State__c is a valid value for the State field, which is the picklist. How can I validate the value before inserting. 
                              State = c.Org_State__c,
                              Country = c.Org_Country__c,
                              email = c.Copy_Contact_Email__c,
                              LastName = c.Contact_Name_Copy__c,
                              LeadSource = 'Department of Commerce Customers',
                              Case_ID__c = c.Id,
                              ITA_Case_Close_Date__c = c.Case_Close_Date__c,
                              ITA_Ref_Case_Number__c = c.ITA_Ref_Case_Number__c,
                             How_did_you_find_this_Company1__c = 'DOC - ' + c.Fee_Based_Service__c
                             ));
                caseLead[counter].setoptions(dmo);
                counter = counter + 1;
        	}

    	}
    	if(caseLead.size() > 0) {
        	insert caseLead;
            Map <ID, Case> matchCases = new Map <ID, Case> (updatedCases);
       		//Now Write the Lead ID Back to the corresponding Case
	  		//matchLeads(updatedCases);
	  		matchLeads(caseLead, matchCases);
        }
        
    	
    }

 
Tavva Sai KrishnaTavva Sai Krishna
Hi Tomeka,

Firstly, sorry for delay.
You can get the picklist values of a field by using the below lines
List<Schema.PicklistEntry>  fieldResult = OfficeLocation__c.Country__c.getDescribe().getPicklistValues();

Here you will get the all the picklist values in  a Schema.PicklistEntry class data type. then you can convert it to a Map of string,string by using this below code.
Map<string,string> options = new Map<string,string>();
for( Schema.PicklistEntry f : fieldResult )
   {
      options.put(f.getLabel(),f.getLabel());
   }

In the options Map you will have all the picklist values. Here you can check the values by this map. 
if(options .get('SA') !=  null){
          system.debug('valid State');
}
else {
           system.debug('Invalid Stage');
}

Let me know if you have any quires. 

Thanks and Regards,
Sai Krishna Tavva.
Tomeka WrayTomeka Wray
I tried above and it isn't returning anything.  I am trying to get the picklist values from the State field on the Lead object. Here is code that I am using. 
 
List<Schema.PicklistEntry>  fieldResult = Lead.State.getDescribe().getPicklistValues();
        system.debug('States = ' + fieldResult);
        
        Map<string,string> options = new Map<string,string>();
		for( Schema.PicklistEntry f : fieldResult )
   			{
      			options.put(f.getLabel(),f.getLabel());
                system.debug('State =' + f.getLabel());
   				}

 
Tavva Sai KrishnaTavva Sai Krishna
Hi Tomeka,

I hope state field is custom field.if you need to use the api name of the field (state__c). I have a picklist field in my lead object whose API name is "Authority__c". I run the below code and it worked fine for me. 

List<Schema.PicklistEntry>  fieldResult = Lead.Authority__c.getDescribe().getPicklistValues();
        system.debug('States = ' + fieldResult);
        
        Map<string,string> options = new Map<string,string>();
for( Schema.PicklistEntry f : fieldResult )
    {
       options.put(f.getLabel(),f.getLabel());
                system.debug('State =' + f.getLabel());
    }


Debug Logs :

see the below image to view the debug logs.

User-added image


Can you post the debug logs/Error you are facing.

waiting for your reply.

Thanks and Regards,
Sai Krishna Tavva.
 
Tomeka WrayTomeka Wray
Here is the debug log. I don't know if it makes a difference, but the state field is part of the Address type, which is a compound field. 

User-added image
Tavva Sai KrishnaTavva Sai Krishna
Hi Tomeka,

By your comment as below "but the state field is part of the Address type, which is a compound field". I see that the state field which is of part of Address standard field is not the picklist type. as it is not the picklist type you cant use the above field. Let me know if i am wrong.
if this is the case we need to store all the state field values as a record in custom settings and do a check with the record before saving.

Let me know if any 
Regards,
Sai Krishna Tavva.
Tomeka WrayTomeka Wray
The field that I needed to query was Lead.statecode. See code below. It returns all of the values for  all of country. Any idea on how to limit to the united states?
 
public static List<Lead> scrubStates (List<Lead> LeadCases){
        List <Lead> validStates = new List<Lead>();
        
        //Gets the value of the valid states
  		List<Schema.PicklistEntry>  fieldResult = Lead.statecode.getDescribe().getPicklistValues();
        system.debug('States = ' + fieldResult);
        
        Map<string,string> options = new Map<string,string>();
		for( Schema.PicklistEntry f : fieldResult )
   			{
      			options.put(f.getLabel(),f.getLabel());
                system.debug('State =' + f.getLabel());
   				}
        for (Lead l : LeadCases){
		
            //Validates case to ensures that the state is valid 
            if(options.get(l.State) !=  null){
         		validStates.add(l);
				}
        }
        system.debug('Before State Scrub = ' + LeadCases.size());
        system.debug('After State Scrub = ' + validStates.size());
        return validStates;
    }

 
Tavva Sai KrishnaTavva Sai Krishna
Hi Tomeka,

I understood that in the options map you are able to get all the picklist values present in the stateCode.(All countries). 
Your query is how to limit it for 'US'.

I got this reference to check the ISO-3166 standard state/country codes.
https://help.salesforce.com/HTViewHelpDoc?id=admin_state_country_picklists_standard_countries.htm&language=en_US (https://help.salesforce.com/HTViewHelpDoc?id=admin_state_country_picklists_standard_countries.htm&language=en_US" target="_blank
with this i made a check in the for loop to the picklist values to the options map . see updated code below.
public static List<Lead> scrubStates (List<Lead> LeadCases){
        List <Lead> validStates = new List<Lead>();
        
        //Gets the value of the valid states
  		List<Schema.PicklistEntry>  fieldResult = Lead.statecode.getDescribe().getPicklistValues();
        system.debug('States = ' + fieldResult);
        
        Map<string,string> options = new Map<string,string>();
		for( Schema.PicklistEntry f : fieldResult )
   			{   
                // Added condition to check the 'US' Country.
				if(f == 'US'){
					options.put(f.getLabel(),f.getLabel());
					system.debug('State =' + f.getLabel());
				}
			}
        for (Lead l : LeadCases){
		
            //Validates case to ensures that the state is valid 
            if(options.get(l.State) !=  null){
         		validStates.add(l);
				}
        }
        system.debug('Before State Scrub = ' + LeadCases.size());
        system.debug('After State Scrub = ' + validStates.size());
        return validStates;
    }
Let me know if it helps or you want any other.
Please mark this as best answer to help others in future.

Thanks and Regards,
Sai Krishna Tavva.
 
This was selected as the best answer
Tavva Sai KrishnaTavva Sai Krishna
Hi Tomeka,

I hope doing well!!. if you get answer to this question please mark it as best answer as it may useful to others. if you have any queriers/issues let me know.

Thanks and Regards,
Sai Krishna Tavva.
Kumaravel MathivananKumaravel Mathivanan
@Tomeka Wray you are right.