In Salesforce World, Metadata plays a very important role. Metadata types and components are used to represent org specific configuration and customization. Salesforce is having a very good page explaining Metadata. Here is the link – “An Introduction to Force.com Metadata“.
Once you have the list, power is completely in your hand. Trust me!! Really you have all the power you need then. You can iterate through the list and get the each CustomMetadataRecord. Now each CustomMetadataRecord is having CustomMetadataValues which also you can fetch and play around.
CustomMetadataValues are stored in two fields – the first one is “field” which stores the API name of the field and the second one is “value” which stores the value of that field for that CustomMetadataRecord. Confused??? Don’t worry I will give you now a clean picture which helped me to understand and I hope it will help you as well.
To understand how the custom metadata information is stored in Salesforce, consider our Custom Metadata Type mentioned above – Admin Preference. And let’s consider one value here –
So according to the above example – Metadata.Operations.retrieve() will retrieve the CustomMetadataRecord – Process Builder Preference. Now this record is having the label – “Process Builder Preference“, which we can get from the label field. The fullName of this record is – “Admin_Preference__mdt.Process_Builder_Preference” which we can get from the method getFullName().
In the above example, this CustomMetadata is having only one value which is stored inside a field of type Metadata.CustomMetadataValue. For that single Metadata.CustomMetadataValue, the field = ‘Enabled__c” and value = true.
So the visual representation of the flow is –
With the above explanation, here comes to code –
The method Metadata.Operations.enqueueDeployment is used to deploy the changes to the org. The operation is happening in asynchronous mode and that is the reason we need to provide a callback method to handle the success/failure scenarios. To create the callback, we need to implement the interface Metadata.DeployCallback and by doing that we need to put our logic in the method – handleResult.
Below is the CallBack method –
Now to deploy the changes below is the code –
You can find the full code in my Github repository.
With all these changes, below is how the functionality working –