I want to write a trigger on a custom object (Template__c) such that it invokes the creation or update of Custom metadata type records. Since the fields are not writeable, how do I achieve this?
I tried using the "CustomMetadataValue". I can see the values assigned in Debug when I run in Anonymous window but the values do not get created in actual.
Best Answer
Custom Metadata Type records are considered Metadata, and as such can't be inserted or updated directly via standard DML operations. Trying to do so will result in a TypeException with a message like:
The
Metadata
namespace was added to Apex in Summer'17/v40.0 and provides the ability to deploy certain types of metadata asynchronously without having to resort the to Metadata API.There is a good example of how this works in the Metadata Operations - Deploy Metadata documentation.
Note that this is an asynchronous operation and you need to provide a callback Apex class that implements the Metadata.DeployCallback interface.
This would be something like:
The DeployResult that comes back via the callback has a number of useful properties that correspond to monitoring an API based Metadata deployment result.
Generally you should rely on the callback to monitor the deployment and then take further actions. However, if you want to be less asynchronous you can use the DeployResultId and the Toolking API to speed things along.
This can't be in the same transaction as the
enqueueDeployment
as it will block subsequent callouts.This example pulls the resulting MetadataComponentId out of the successfully deployed components.