How to add multiple value to a multipicklist from apex

  • I am trying to add multiple value to a multipicklist from apex. I put the value into a list of string and added it don't allow to add, try to add using a string split by ',' but it get added as a single record try to add one by one in this case only the last record get saved. How can i achieve it. Please help me to get the solution.

    List<String> picklistValues = new List<String>();
    String selected;
    picklistValues  = itemChoiceSetconfigItemCodeMap.get(configItemsID);
    for(String picklistValue : picklistValues){
       // Add pick list values
       configItem.Chose_Code__c = picklistValue;
    }
    //configItem.Chose_Code__c = picklistValues  ;
    

    Please guide me a best way to do this.

  • These are methods I use for this purpose:

    public static String format(Set<String> values) {
        if (values == null) return null;
        List<String> l = new List<String>(values);
        l.sort();
        return format(l);
    }
    
    public static String format(List<String> values) {
        if (values == null) return null;
        return String.join(values, ';');
    }
    

    so in your case:

    configItem.Chose_Code__c = format(picklistValues);
    
  • Multi-select picklist values are stored as a semicolon separated string.

    Thus to set a value via apex containing options 'a', 'b and 'c', you'd have something like:

    configItem.Chose_Code__c='a;b;c';
    
  • You can add values in a picklist like the following example.

    Public String SelectedOppr {set; get;}
     Public List<SelectOption> getOpprortunities(){
          list<SelectOption> OpprList = new list<SelectOption>();     
          for( Opportunity o: childList){ //childList contains the records 
            OpprList.Add(New SelectOption(o.Id,o.Name));     
          }
          return OpprList;
        }
    

    In vf page, you can use this as :

     <apex:selectList value="{!SelectedOppr}" size="5" multiselect="true">
                  <apex:selectOptions value="{!Opprortunities}" >
                  </apex:selectOptions>
            </apex:selectList>
    

    Let me know if this helps.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM