function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Wilfredo Morillo 20Wilfredo Morillo 20 

Multi-Picklist: Add or Remove value apex function

I created this function to add or remove selected values in a multipicklist. It works but I'm trying to simplify it. Any comments or suggestions are truly apriciated. 
 
// This function returns an string with the values for a multipicklist after adding or removing an input Value.
	Public Static String MultipicklistUpdate(String currentValues,String inputValue,boolean addValue){
            
            list<String> allValues = new List<String>();
            boolean inputExist = false;
            
            String newValue = null;
            
            If (!(currentValues == '' || currentValues ==null)){
               
                allValues = currentValues.split(';');
    
                for(String value :allValues){
                    if(value == inputValue){
                      inputExist = true;  
                      if(addValue == true)newValue =+';'+ value;
                    }else{
                        if(newValue==null){
                             newValue =+ value;
                        }else {
                           newValue = newValue +';'+ value; 
                       }  
                    }
                }  
            }
            If(addValue == true && inputExist == false){
                if(newValue == null){
                    newValue = inputValue;
                }else{
               newValue = newValue+ ';'+inputValue;
                }
            }
            return newValue;
    }

 
Damon ShawDamon Shaw
Hi Wilfredo,

I would put the current values into a map and then use the remove or put functions depending on your boolean
 
// This function returns an string with the values for a multipicklist after adding or removing an input Value.
Public Static String MultipicklistUpdate(String currentValues,String inputValue,boolean addValue){

    if(!String.isBlank(currentValues)){
        Map<String, String> currentValueMap = new Map<String, String>();
        for(String s :currentValues.split(';')){
            currentValueMap.put(s,s);
        }

        if(addValue && !currentValueMap.containsKey(inputValue)){
            currentValueMap.put(inputValue, inputValue);
        }
        else{
            if(currentValueMap.containsKey(inputValue)){
                currentValueMap.remove(inputValue);
            }
        }

        String newValue = '';
        for(String s :currentValueMap.values()){
            newValue = newValue+ ';'+inputValue;
        }

        return newValue;
    }
    else if(addValue && !String.isBlank(inputValue)){
        return inputValue;
    }

    return null;
}