In this blog post, we will guide you through the steps to achieve this.
Prerequisites: Before starting, ensure that you have the following:
- A Salesforce Developer Edition org or a sandbox environment.
- The MetadataService class added to your Salesforce org.
Step 1: Establish a Metadata Service Instance
The first step is to create an instance of the MetadataService.MetadataPort class. This class provides methods for creating, reading, updating, and deleting metadata components.
The first step is to create an instance of the MetadataService.MetadataPort class. This class provides methods for creating, reading, updating, and deleting metadata components.
MetadataService.MetadataPort service = createService();
Step 2: Define the Custom Field
Next, we define the custom field that we want to create. We specify the field’s API name, label, and type. In this case, we’re creating a picklist field.
metadataservice.ValueSet vs = new metadataservice.ValueSet(); vs.controllingField = 'controlling_field__c'; metadataservice.ValueSetValuesDefinition vd = new metadataservice.ValueSetValuesDefinition(); vd.sorted= false; metadataservice.CustomValue one = new metadataservice.CustomValue(); one.fullName= 'first'; one.default_x=false ; vd.value = new List<MetadataService.CustomValue>{one}; vs.valueSetDefinition = vd; customField.valueSet = vs;
Step 3: Define the Picklist Values
We then define the picklist values that we want to add to our custom field. We create an instance of metadataservice.ValueSet and metadataservice.ValueSetValuesDefinition. We also create instances of metadataservice.CustomValue for each picklist value.
We then define the picklist values that we want to add to our custom field. We create an instance of metadataservice.ValueSet and metadataservice.ValueSetValuesDefinition. We also create instances of metadataservice.CustomValue for each picklist value. metadataservice.ValueSet vs = new metadataservice.ValueSet(); vs.controllingField = 'controlling_field__c'; metadataservice.ValueSetValuesDefinition vd = new metadataservice.ValueSetValuesDefinition(); vd.sorted= false; metadataservice.CustomValue one = new metadataservice.CustomValue(); one.fullName= 'first'; one.default_x=false ; vd.value = new List<MetadataService.CustomValue>{one}; vs.valueSetDefinition = vd; customField.valueSet = vs;
Step 4: Create the Custom Field
Finally, we call the createMetadata method on our service instance to create the custom field. We pass in an array of metadata components that we want to create.
List<MetadataService.SaveResult> results = service.createMetadata( new MetadataService.Metadata[] { customField }); handleSaveResults(results[0]);
Conclusion
And that’s it! You’ve just created a custom picklist field using Salesforce Metadata API. You can use similar steps to update or delete metadata components.