Salesforce | How to Update the Values of a Custom Picklist Field using Metadata API?

The user can easily add, delete, or update the values of a custom picklist field manually. But there are times when you have to update and add the values of the custom picklist field by using code. That’s when metadata API comes to the rescue. For understanding metadata API, you can visit – Metadata, Custom Metadata Types, and Metadata API.

Now, for updating the values of the custom picklist field there are two classes required:

  1. MetadataService.cls: You can find this class available on the internet as well but there are modifications done according to this scenario in this class. 
  1. We need to create another class for updating the values of a custom picklist field. The class we are calling here is updatingCustomPicklistValues. For this, we need a custom Picklist field on any object. 

Here, the object we have taken is Opportunity and we have a custom picklist field named Picklist_check 

Don’t forget to check out: Visualizing Salesforce Metadata: Understanding the Relationships with AbstraLinx ERDs

Updating Custom Picklist Values 

public class UpdatingCustomPicklistValues { 
// Method to update the values of custom picklist field 
     public static void updatePicklistValues() { 
          MetadataService.MetadataPort service = new MetadataService.MetadataPort(); 
          service.SessionHeader = new MetadataService.SessionHeader_element(); 
          service.SessionHeader.sessionId = UserInfo.getSessionId(); 
          MetadataService.ValueSet picklistValueSet = new MetadataService.ValueSet(); 
          MetadataService.ValueSetValuesDefinition valueDefinition = new MetadataService.ValueSetValuesDefinition(); 
          List<MetadataService.ExtendedCustomValue> values = new List<MetadataService.ExtendedCustomValue>(); 
          // Fetching the values already available in the custom picklist field and storing them in the list 
          List<Schema.PicklistEntry> picklistValues = Opportunity.Picklist_check__c.getDescribe().getPicklistValues();
          // Adding the already available values 
               for(Schema.PicklistEntry picklistValue : picklistValues) { 
                    MetadataService.ExtendedCustomValue customValue1 = new MetadataService.ExtendedCustomValue(); 
                    customValue1.fullname = (string)picklistValue.getValue(); 
                    customValue1.default_x = false; 
                    customValue1.isActive = true; 
                    customValue1.label = picklistValue.getLabel(); 
                    values.add(customValue1); 
               } 
          //Adding the extra value, we want to add 
          MetadataService.ExtendedCustomValue customValue2 = new MetadataService.ExtendedCustomValue(); 
          customValue2.fullname = ‘1’; 
          customValue2.default_x = false; 
          customValue2.isActive = true;
          customValue2.label = ‘1’; 
          values.add(customValue2);
          valueDefinition.value = values; 
          valueDefinition.sorted = true; 
          picklistValueSet.valueSetDefinition = valueDefinition; 
          MetadataService.CustomField customField = new MetadataService.CustomField(); 
          customField.fullName=" Opportunity.Picklist_check__c "; 
          customField.label=" Picklist_check "; 
          customField.type_x = 'Picklist'; 
          customField.required = false; 
          customField.unique = false; 
          customField.valueSet = picklistValueSet;
          MetadataService.CustomField[] customFields = new List<MetadataService.CustomField> { customField }; 
          service.upsertMetadata(customFields); 
     } 
     // Method to save the work done 
     public static void handleSaveResults(MetadataService.SaveResult saveResult) 
          { 
          if(saveResult==null || saveResult.success) 
          return; 
          // Construct error message and throw an exception 
          if(saveResult.errors!=null) 
               {
                    List<String> messages = new List<String>(); 
                    messages.add( 
                    (saveResult.errors.size()==1 ? 'Error ' : 'Errors ') + 
                    'occured processing component ' + saveResult.fullName + '.'); 
                    for(MetadataService.Error error : saveResult.errors) 
                    messages.add( 
                    error.message + ' (' + error.statusCode + ').' + 
                    ( error.fields!=null && error.fields.size()>0 ? 
                    ' Fields ' + String.join(error.fields, ',') + '.' : '' ) ); 
                    if(messages.size()>0) 
                    throw new MetadataServiceExamplesException(String.join(messages, ' ')); 
               } 
          if (!saveResult.success) 
          throw new MetadataServiceExamplesException('Request failed with no specified error.'); 
     } 
     //Method to create an instance of MetadataService.MetadataPort 
     public static MetadataService.MetadataPort createService() 
     { 
          MetadataService.MetadataPort service = new MetadataService.MetadataPort(); 
          service.SessionHeader = new MetadataService.SessionHeader_element(); 
          service.SessionHeader.sessionId = UserInfo.getSessionId(); 
          return service; 
     } 
     public class MetadataServiceExamplesException extends Exception { } 
}

dont miss out iconCheck out another amazing blog by Navdita here: What is the Grant Management System in Salesforce? | All You Need to Know

Now , in the Developer console, save both classes. Then, click on Debug. Then, click Open Execute Anonymous Window. Copy and paste the following code in the anonymous window- 

UpdatingCustomPicklistValues.UpdatePicklistValues();

And Yaa, it’s done. 

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *