[SalesForce] Create Picklist using Metadata API

I am using Metadata API to create various fields. For most part it works, but not for Picklist type. Seems like I am missing picklistValues[]

API version 39

This is working

customField = new MetadataService.CustomField();
customField.fullName = sObj + '.Text__c';
customField.label = 'Test';
customField.type_x = 'Text';
customField.description = 'Test.';
customField.length = 255;
customFields.add(customField); 

This is NOT working

customField = new MetadataService.CustomField();
customField.fullName = sObj + '.Segment__c';
customField.label = 'Segment';
customField.type_x = 'Picklist';
customField.description = '';
customFields.add(customField); 

Best Answer

For creating picklist using Metadata API, use the following code:

customField = new MetadataService.CustomField();
customField.fullName = sObj + '.Segment__c';
customField.label = 'Segment';
customField.type_x = 'Picklist';
customField.description = '';

//Create the valueSet for picklist type
MetadataService.ValueSet picklistValueSet = new MetadataService.ValueSet();

//For each ValueSet, we have either ValueSetValuesDefinition or ValueSettings and some other attributes
MetadataService.ValueSetValuesDefinition valueDefinition = new MetadataService.ValueSetValuesDefinition();

List<MetadataService.CustomValue> values = new List<MetadataService.CustomValue>();

MetadataService.CustomValue customValue1 = new MetadataService.CustomValue();
customValue1.fullName = ''; //API name of picklist value
customValue1.default = true/false;
customValue1.description = '';
customValue1.isActive = true/false;
customValue1.label = '';
values.add(customValue1);

//It will be list of CustomValue
valueDefinition.value = values;
valueDefinition.sorted = false/true;

//set the valueSetDefinition
picklistValueSet.valueSetDefinition = valueDefinition;

//Set the valueSet for picklist type
customField.valueSet = picklistValueSet;
customFields.add(customField); 

Description: For picklist, we need to set the valueset attribute which is of type ValueSet.

For type ValueSet, create valueSetDefinition which is of type ValueSetValuesDefinition.

For type ValueSetValuesDefinition, create value which is of type List of CustomValue.

Refer Metadata API types

Related Topic