+ Start a Discussion
JeffStevensJeffStevens 

Looping through multi-select picklist values

Could I get simple example of how to loop through a multi-select picklist field?

 

Thanks!

Starz26Starz26

Which are you trying to do:

 

1. Loop through the values selected

 

Account a = [Select AMSPICKLIST__c From account Limit 1];

 

String[] tmpString = a.AMSPICKLIST__c.split(';');

 

For(Stirng s : tmpString)

   system.debug(s);

 

 

2. Loop through the available options to select from?

 

public List<selectOption> getPickValues(Sobject object_name, String field_name, String first_val) {
      List<selectOption> options = new List<selectOption>(); //new list for holding all of the picklist options
      if (first_val != null) { //if there is a first value being provided
         options.add(new selectOption(first_val, first_val)); //add the first option
      }
      Schema.sObjectType sobject_type = object_name.getSObjectType(); //grab the sobject that was passed
      Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); //describe the sobject
      Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); //get a map of fields for the passed sobject
      List<Schema.PicklistEntry> pick_list_values = field_map.get(field_name).getDescribe().getPickListValues(); //grab the list of picklist values for the passed field on the sobject
      for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
         if(a.getValue() != 'unknown' && a.getValue() != 'Other' )         
            options.add(new selectOption(a.getValue(), a.getLabel())); //add the value and label to our final list
      }
      return options; //return the List
}

 Then to loop through it:

 

For(SelectOption so : RESULTS)

   system.debug(so.value());

 

 

AsiereikiAsiereiki
This in multipicklist like strings splitted by  ";". the rest is easy.
Pasan  EeriyagamaPasan Eeriyagama
I wonder how do I retrieve selected values from mulit-picklist field.. Above always return all the values it seems.
Sagar Nagvekar 14Sagar Nagvekar 14
For identifying only the selected values from a multi-select picklist Cars__c from Account :-
Account accountRecord = [select id, name, Cars__c from Account where name = 'Microsoft India'];
String[] carsOwned = accountRecord.Cars__c.split(';');
System.debug('Cars owned by this account are ' + carsOwned);