-2

Context

We need to export picklist label and API values for several objects, in a csv file using apex.

Several posts exist on this subject but the objective is to export picklist values for several objects at once, not only for a single object.

This question aims to be a knowledge sharing post and provides a working script how this requirement can be achieved

1
  • May I know the reason of the downvote?
    – Shamina
    Commented Jun 10, 2023 at 4:50

1 Answer 1

0

Here's a sample apex code to achieve this requirement.

Hope this helps someone looking to achieve something similar

Set<String> setObjects = new Set<String>{'Account','Contact'}; //list your objects' API name including custom object, note that too many objects can cause Apex CPU limit exceeded
String generatedCSVFile ='Object;FieldName;Label;APIName'+ '\n';

for (String apiname: setObjects ){
String fileRow = '';
    String objectName = apiname;
    system.debug(objectName );

    SObjectType r = Schema.getGlobalDescribe().get(objectName) ;
    DescribeSObjectResult d = r.getDescribe();
    Map<String, Schema.SObjectField> mapfields = d.fields.getMap();

    for(String fieldn : mapfields.keyset()){
        String fieldName =fieldn ;
        Schema.DescribeFieldResult fieldResult = mapfields.get(fieldn).getDescribe();
        if(fieldResult.getType() == Schema.DisplayType.PICKLIST){

           List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
           for( Schema.PicklistEntry pickListVal : ple){
              //System.debug(pickListVal.getLabel() +' '+pickListVal.getValue());
              fileRow = '';
              //change csv delimiter accordingly
              fileRow = fileRow +';'+ objectName; 
              fileRow = fileRow +';'+ fieldName;
              fileRow = fileRow +';'+ pickListVal.getLabel();
              fileRow = fileRow +';'+ pickListVal.getValue();
              fileRow = fileRow.replaceFirst(';','');
              generatedCSVFile = generatedCSVFile + fileRow + '\n';
           }
        }
    }

}

system.debug(generatedCSVFile );

ContentVersion cv = new ContentVersion();
cv.firstPublishLocationId= UserInfo.getUserId();
cv.Title = 'PicklistExtract'; 
cv.pathOnClient = 'PicklistExtract.csv'; 
cv.VersionData = Blob.valueOf(generatedCSVFile); //file data
insert cv; //file is saved current user's my files

This answer is inspired and derived by related answers on these posts, thanks to the contributors

How to dynamically query any Field's Picklist values using Apex

Get the type (data type) of a field in apex

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .