Skip to content

Instantly share code, notes, and snippets.

@ykurnia
Last active August 12, 2022 07:39
Show Gist options
  • Save ykurnia/26b6227ad77658559a62b47f8ea91003 to your computer and use it in GitHub Desktop.
Save ykurnia/26b6227ad77658559a62b47f8ea91003 to your computer and use it in GitHub Desktop.
Contoh Update/Insert Custom Metadata Type di Salesforce
/*// update metadata type that save the counter
Di contoh ini, Custom Metadata bernama OrderLineCounter__mdt
Custom fields : Prefix__c (text), Counter__c (integer)
Input adalah map<string, Integer> berisi daftar data yang ingin diupdate/insert (bisa lebih dari satu)
*/
@future
public static void UpdateCounterMetadata(Map<String, Integer> mapCount)
{
Map<String, OrderLineCounter__mdt> mapMDT = new Map<String, OrderLineCounter__mdt>(); // prefix -> metadata
OrderLineCounter__mdt objMDT;
Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
Metadata.CustomMetadataValue tmpMDValue;
Metadata.CustomMetadata metadataRec;
String strTmp;
for (OrderLineCounter__mdt C: [SELECT Id,MasterLabel,DeveloperName, Prefix__c, Counter__c
FROM OrderLineCounter__mdt WHERE Prefix__c IN :mapCount.keySet() ])
{
mapMDT.put(String.valueOf(C.Prefix__c), C);
}
for(String s: mapCount.keySet()) {
metadataRec = new Metadata.CustomMetadata();
if (mapMDT.get(s) != null) { //update
objMDT = mapMDT.get(s);
metadataRec.fullName = 'OrderLineCounter__mdt.' + objMDT.DeveloperName;
metadataRec.label = objMDT.MasterLabel;
}
else { // insert
strTmp = String.valueOf(s);
metadataRec.fullName = 'OrderLineCounter__mdt.' + strTmp;
metadataRec.label = strTmp;
tmpMDValue = new Metadata.CustomMetadataValue();
tmpMDValue.field = 'Prefix__c';
tmpMDValue.value = s;
metadataRec.values.add(tmpMDValue);
}
tmpMDValue = new Metadata.CustomMetadataValue();
tmpMDValue.field = 'Counter__c';
tmpMDValue.value = mapCount.get(s);
metadataRec.values.add(tmpMDValue);
mdContainer.addMetadata(metadataRec);
}
system.debug('DEBUG: updating metadata ' + mapCount);
if (!Test.isRunningTest()) {
Metadata.Operations.enqueueDeployment(mdContainer, null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment