1

Is it possible to add new values to a picklist from apex code. I my trigger I am getting a set of picklist values now I need to add all these values to a picklist field on my object. Please help me out to get the solution for this issue.

0
1

yes it is possible to add new piclist value dynamically. I'm not sure about the trigger but ya we can do that by using Metadata services. In the following code we adding new value to the piclist field in Lead. If this can help you :-

public static void UpdatePicklistField()
    {
        MetadataService.MetadataPort service = createService();    
        MetadataService.CustomField customField = new MetadataService.CustomField();
        customField.fullName = 'Lead.picklist__c';       // your object. fields name
        customField.label = 'picklist';                 // label of field.
        customField.type_x = 'Picklist';               // type
        metadataservice.Picklist pt = new metadataservice.Picklist();
        pt.sorted= false;
        metadataservice.PicklistValue two = new metadataservice.PicklistValue(); //new value
        two.fullName= 'second';
        two.default_x=false ;
        metadataservice.PicklistValue three = new metadataservice.PicklistValue(); // new value
        three.fullName= 'third';
        three.default_x=false ;
        pt.picklistValues = new list<metadataservice.PicklistValue>{two,three};  
        customField.picklist = pt ;
        MetadataService.UpdateMetadata ut = new MetadataService.UpdateMetadata(); // here you are updated your value in object.
        ut.currentName='Lead.picklist__c';
        ut.metadata= customField;  
        MetadataService.AsyncResult[] results = service.updateMetadata(new List<MetadataService.updateMetadata> {ut});
    }
 public static MetadataService.MetadataPort createService()

    {
        MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = UserInfo.getSessionId();
        return service;    
    }
1
  • On making this call from a trigger, it can by made via a method marked @future which means the picklist will be updated sometime later. – Keith C Jun 11 '15 at 8:33
-3

Please refer this link. This is similar to your requirement. Let me know if this helps.

1
  • Saroj, please do more than posting a URL. Explain the essensial parts that will answer the question and user the link as reference. That way we make sure the answer is provided here, and not on a website that may dissapear. – Samuel De Rycke Jun 11 '15 at 8:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.