Skip to content

Instantly share code, notes, and snippets.

@Patlatus
Created October 18, 2018 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Patlatus/53ce49fde265c0aa3d0f2c3fdda8b900 to your computer and use it in GitHub Desktop.
Save Patlatus/53ce49fde265c0aa3d0f2c3fdda8b900 to your computer and use it in GitHub Desktop.
MD.apex
public class MD {
public static List<String> getItems(List<String> parts, Map<String, Schema.SObjectField> fieldsMap, SObject r) {
List<String> items = new List<String>();
for (String part: parts) {
items.add( fieldsMap.containsKey( part ) ? String.valueOf( r.get( part ) ) : part );
}
return items;
}
public static Id updateAndDeployMetadata(List<SObject> sourceRecords, SObjectType dest, Map<SObjectField, SObjectField> mappings, String fullNameDef, String labelDef) {
Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
String destName = dest.getDescribe().getName();
List<String> fullNameParts = fullNameDef.split('\\+');
List<String> labelParts = labelDef.split('\\+');
if( sourceRecords != null && !sourceRecords.isEmpty() ) {
Map<String, Schema.SObjectField> fields = sourceRecords[0].getSObjectType().getDescribe().fields.getMap();
for (SObject r: sourceRecords ) {
Metadata.CustomMetadata customMetadata = new Metadata.CustomMetadata();
customMetadata.fullName = destName + '.' + String.join( getItems(fullNameParts, fields, r), '');
customMetadata.label = String.join( getItems(labelParts, fields, r), '').left(40);
for (SObjectField key: mappings.keySet() ) {
Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue();
customField.field = String.valueOf( mappings.get(key) );
customField.value = r.get(key);
customMetadata.values.add(customField);
}
mdContainer.addMetadata(customMetadata);
}
return Metadata.Operations.enqueueDeployment(mdContainer, null);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment