Created
July 4, 2022 22:02
-
-
Save iamsonal/6e0f75c2eec43ddffe956afd3b653a31 to your computer and use it in GitHub Desktop.
Update Picklist in Salesforce using Metadata API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MetadataApiService.MetadataPort service = createService(); | |
MetadataApiService.CustomField customField = (MetadataApiService.CustomField) service.readMetadata('CustomField', new String[]{ | |
'Account.Demo__c' | |
}).getRecords()[0]; | |
MetadataApiService.GlobalValueSet globalValueSet = (MetadataApiService.GlobalValueSet) service.readMetadata('GlobalValueSet', | |
new List<String>{ | |
customField.valueSet.valueSetName | |
}).getRecords()[0]; | |
List<MetadataApiService.CustomValue> customValues = new List<MetadataApiService.CustomValue>(); | |
for (CustType__c custType : relevantCustTypes) { | |
MetadataApiService.CustomValue customValue = globalValueSet.customValue[0].clone(); | |
customValue.label = custType.Name; | |
customValue.fullName = custType.Name; | |
customValues.add(customValue); | |
} | |
globalValueSet.customValue.addAll(customValues); | |
List<MetadataApiService.Metadata> metadataList = new List<MetadataApiService.Metadata>(); | |
metadataList.add(globalValueSet); | |
List<MetadataApiService.SaveResult> saveResults = service.updateMetadata(metadataList); | |
for (MetadataApiService.SaveResult saveResult : saveResults) { | |
if (saveResult.success) { | |
System.debug('Successfully updated'); | |
} else { | |
if (saveResult.errors.size() > 0) { | |
System.debug('Error : ' + saveResult.errors[0].message); | |
throw new MetadataServiceExamplesException('Error : ' + saveResult.errors[0].message); | |
} | |
} | |
} | |
public static MetadataApiService.MetadataPort createService() { | |
MetadataApiService.MetadataPort service = new MetadataApiService.MetadataPort(); | |
service.AllOrNoneHeader = new MetadataApiService.AllOrNoneHeader_element(); | |
service.AllOrNoneHeader.allOrNone = true; | |
service.SessionHeader = new MetadataApiService.SessionHeader_element(); | |
service.SessionHeader.sessionId = UserInfo.getSessionId(); | |
service.timeout_x = 120000; | |
return service; | |
} | |
private class MetadataServiceExamplesException extends Exception { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment