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
Arjun KVArjun KV 

Add value to multiselect picklist through apex code.

Hi All,

How to add value to the multiselect Picklist through apex code.
I have a requirement to get the value from one Object's text field and  add that values to Multiselect pick list field in another object.


 
Vishal NegandhiVishal Negandhi
So, do you mean add those values as new picklist options?
Or do we have two fields with same/similar options and you just want to copy from one record and update the other?
Sudipta DebSudipta Deb
You can do this using trigger. Below example is doing this -
In the Student object, I have a multiselect Pick List Interest__c and I have a text field named Other_Interest__c. If I add anything in the text field (Other_Interest__c), the same value will be added to the multiselect pick list.I hope this will help you to understand -

Trigger StudentTrigger -
trigger StudentTrigger on Student__c (after delete, after insert, after undelete, 
										after update, before delete, before insert, before update) {
	if(Trigger.isBefore){
		if(Trigger.isInsert || Trigger.isUpdate){
			StudentTriggerHelper.updateRating(trigger.new);
		}
	}
}
And now the helper class StudentTriggerHelper -
public class StudentTriggerHelper {
	public static void updateRating(List<Student__c> allStudents){
		for(Student__c eachStudent : allStudents){
			//If user put something in the other interest field and the new interest is not present in the multiselect option
			//then only do the operation
			if((eachStudent.Other_Interest__c != null) && 
				isNewInterest(eachStudent.Interest__c.split(';'), eachStudent.Other_Interest__c)){
				eachStudent.Interest__c = eachStudent.Interest__c + ';' + eachStudent.Other_Interest__c;
				eachStudent.Other_Interest__c = '';
			}
		}
	}
	
	
	private static Boolean isNewInterest(String[] selectedInterests, String newInterest){
		for(String eachInterest : selectedInterests){
			if(eachInterest.equalsIgnoreCase(newInterest)){
				return false;
			}
		}
		return true;
	}
}

Below is few screenshots for your reference -
Edit Page Where I am inserted a new Interest "Photography"

After save, we can see the new interest

If we edit again, we can see the new interest in the multi select option also

Please let me know if you need any feedback. Thanks.
Arjun KVArjun KV
Hi Vishal,
I need to add those value as MultiselectPickList Options
Arjun KVArjun KV
Hi Sudipta,

Thanks for your response.
Let me explain you my senario. I have two custom object Test__c and Testing__c. In Test__c i have a text field called Partner_level__c and in Testing__c i have a MultiSelectPicklistField called Pick_List__c.
When i enter value at Partner_Level__c at Test__c object that value must add to MultiPicklist in Testing__c .

By looking at your code i tried following thing but I am getting error while assigning new value to MultiSelectPicklistField.
Please Look at the code below and provide your input.

Error:Compile Error: Expression cannot be assigned.    


Trigger:
trigger PickListTrigger on Test__c (after delete, after insert, after undelete,after update, before delete, before insert, before update) {
 if(Trigger.isBefore)
 {
  if(Trigger.isInsert || Trigger.isUpdate)
  {
    PickListTriggerHelper.UpdatePartnerLevel(trigger.new);
  }
 }
}

HelperClass:
public class PickListTriggerHelper {
      public static void UpdatePartnerLevel(List<Test__c> PartnerLevel)
      {
          Schema.DescribeFieldResult Pickvalue= Testing__c.Pick_List__c.getDescribe();
List<Schema.PicklistEntry> PickListValue = Pickvalue.getPicklistValues();
list<string> str= new list<string>();
    for(schema.picklistEntry p:PickListValue){
       str.add(string.valueof(p));
    }

           for(Test__c eachPartnerLevel:PartnerLevel)   
         {
           if((eachPartnerLevel.Partner_Level__c!=null)&&isNewPickList(str,eachPartnerLevel.Partner_Level__c))
           {
               Testing__c.Pick_List__c=Testing__c.Pick_List__c + ';' + eachPartnerLevel.Partner_Level__c;
           }
         }
      }
    private static Boolean isNewPickList(list<String> existingPartnerLevels,String newPartnerLevel)
    {
        for(String eachLevel:existingPartnerLevels)
        {
            if(eachLevel.equalsIgnoreCase(newPartnerLevel)){
              return false;
            }
        }
        return true;
     }
}
Sudipta DebSudipta Deb
Hi Arjun -

Please check the below code.

Assumptions:
  • There should be a relationship between Test__c and Testing__c. The below code assumes that there is a lookup relationship between Test__c and Testing__c. The schema diagram is given below for your reference -
Schema

Below you will find the code -
Trigger:
trigger TriggerOnTest on Test__c (after delete, after insert, after undelete, 
after update, before delete, before insert, before update) {
	if(Trigger.isBefore){
		if(Trigger.isInsert || Trigger.isUpdate){
			TestHelper.updatePickList(trigger.new);
		}
	}
}
Helper Class:
public class TestHelper {
	public static void updatePickList(List<Test__c> allTests){
		List<Testing__c> allTesting = new List<Testing__c>();
		
		for(Test__c eachTest : allTests){
			if(eachTest.Partner_Level__c != null){
				Testing__c aTesting = [SELECT Pick_List__c from Testing__c WHERE ID = : eachTest.Testing_Reference__c];
				if(isNewValue(eachTest.Partner_Level__c, aTesting.Pick_List__c.split(';'))){
					aTesting.Pick_List__c = aTesting.Pick_List__c + ';' + eachTest.Partner_Level__c;
					allTesting.add(aTesting);
				}
			}
		}
		
		update allTesting;
	}
	
	private static Boolean isNewValue(String newValue, String[] selectedValues){
		for(String eachValue : selectedValues){
			if(eachValue.equalsIgnoreCase(newValue)){
				return false;
			}
		}
		return true;
	}
}

The screenshots are given below:
Initially TESTING 3 looks like -
Initially Testing 3 looks like this
Now I have added a record TEST 3 and I put "VALUE 10" in the Partner Level field.
User-added image
Now the same value i.e. "VALUE 10" is added to the multiselect picklist in TESTING 3.
User-added image

If this code helps, requesting you to please choose this as Best Answer and mark the question as Solved.
HARI KRISHNAHARI KRISHNA
Hi Sudipta Deb,

I want to add that new picklist value in Available values not in Chosen Value. For this any solution. 

Hari Krishna,
SFDC.
Rafael.Martins.SantosRafael.Martins.Santos
Hi,

I'm new with APEX, and I need know how populate a Select Field in Opportunity with a list of campaign Name.
I don't understand the code above, but I created the follow code and by this way I can list all campaign name, but I don't know how insert into a select field.

public class Opportunity{

public List<SelectOption> getCampanhas(){
    List<SelectOption> options = new List<SelectOption>();
    List<Campaign> campanhas = [SELECT Id, Name, IsActive FROM Campaign WHERE IsActive = true];
    
    
    for(Campaign c:campanhas){
        options.add(new SelectOption(c.Name, c.Name));       
    }
    return options;   
}
}
Opportunity p = new Opportunity();
System.debug(p.getCampanhas());


Can someone help me?

Best Regards
Rafael