[SalesForce] How to remove an option from mutli-picklist field in apex trigger

I want to write an apex trigger action to remove a particular value from multi select picklist field based on some condition.How can I do this?

This is my trigger action:

public static void updateStopCom(map<Id, Account> accountOldMap, map<Id, Account> accountNewMap) {
   for (Id accountId : accountNewMap.keySet()) {
        Account newAccountValue = accountNewMap.get(accountId);
        Account prevAccountValue = accountOldMap.get(accountId);
        if ( (newAccountValue.Online__pc != prevAccountValue.Online__pc)){

             if(newAccountValue.Online__pc == true){
                newAccountValue.StopCom__c = ???; // how?
             }

        }
   }
}

StopCom__c is my multi select picklist field.

Could anyone please help me to resolve this?

Best Answer

As multiselect picklist fields are stored as semi colon separated values, you will have to follow below steps to add/remove values to/from it.

  • Split the values by semi colon and convert the string into List
  • Add/Remove the element to/from the list
  • Convert the list back to semi colon separated values using String.Join method

This is how your code should look like

string strPickListValue = newAccountValue.StopCom__c;
List<string> lstPicklistValues = strPickListValue.split(';');
string strValueToRemove ='abc';
if(lstPicklistValues.contains(strValueToRemove)){
    lstPicklistValues.remove(lstPicklistValues.indexOf(strValueToRemove));
}
newAccountValue.StopCom__c = String.join(lstPicklistValues,';');