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
Diwakar GDiwakar G 

Adding a new value to the existing picklist field of an object using Apex

Hi, I want add a new value to the existing picklist field of an object using Apex. Please help me.
Akshay_DhimanAkshay_Dhiman
Hi Diwakar,

The way to do this is using the Apex MetaData API wrapper as provided by esteemed SFSE colleague Andrew Fawcett here --

   1-  Running user needs to have Customize Application privilege so you really want this to be an admin type user
   2- Read the examples in the GIT package carefully - there is one for picklists. You need to read the CustomField from the MetaData API first then update, otherwise you'll smash all the existing picklist entries.
 
public static void updatePicklistField()
    {
        MetadataService.MetadataPort service = createService();
        MetadataService.CustomField customField = new MetadataService.CustomField();
        customField.fullName = 'Lead.picklist__c';
        customField.label = 'picklist';
        customField.type_x = 'Picklist';
        metadataservice.Picklist pt = new metadataservice.Picklist();
        pt.sorted= false;
        metadataservice.PicklistValue two = new metadataservice.PicklistValue();
        two.fullName= 'second';
        two.default_x=false ;
        metadataservice.PicklistValue three = new metadataservice.PicklistValue();
        three.fullName= 'third';
        three.default_x=false ;
        pt.picklistValues = new list<metadataservice.PicklistValue>{two,three};
        customField.picklist = pt ;
        List<MetadataService.SaveResult> results =
            service.updateMetadata(
                new MetadataService.Metadata[] { customField });
        handleSaveResults(results[0]);
    }

Please select it as Best answer if you find it helpful.

Thanks 
Akshay