-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUpdateCMD.cls
147 lines (135 loc) · 8.1 KB
/
UpdateCMD.cls
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/**
* @description : This invocable class will allow you to update/create customMetadata using Flow/Process Builder.
* @author : M Hamza Siddiqui @ mhamzas.com
* @group : Cloudjunction Advisors, Inc.
* @last modified on : 01-21-2021
* @last modified by : M Hamza Siddiqui @ mhamzas.com
* Modifications Log
* -----------------
* Ver Date Author Modification
* 1.0 01-22-2021 M Hamza Siddiqui @ mhamzas.com Initial Version
**/
global class UpdateCMD implements Metadata.DeployCallback {
/*An invocable variable used as input or output variables in the process builder*/
global class ActionRequest {
@InvocableVariable(required = true)
public List<sObject> data;
}
//This invocable method is used for processing the business by taking the input from process builder/flow
@InvocableMethod(label = 'Create/Update Custom Metadata')
global static void invokeService(List <ActionRequest> requests) {
for (ActionRequest requestObj: requests) {
//Accessing the values from process builder/flow when record is inserted
for(sObject obj : requestObj.data){
//System.debug('requestObj.sObject@@:' + obj);
//System.debug('requestObj.ObjectType@@:' + obj.getSObjectType());
String ObjectType = String.valueof(obj.getSObjectType());
if(ObjectType.endsWith('__mdt') == TRUE){
// Getting all the Populated fields in a Map
Map<String, Object> fieldsToValue = obj.getPopulatedFieldsAsMap();
Map<String, Object> metadataFieldValueMap = new Map<String, Object>();
String MetadataDevName; // To Store Custom Metadata Record API/Developer name
String MetadataLabel; // To Store Custom Metadata Label name
// Looping on all the populated fields
for (String fieldName : fieldsToValue.keySet()){
//System.debug('field name is ' + fieldName + ', value is ' + fieldsToValue.get(fieldName));
// We don't want to add system fields to the Map for update, so here is some simple logic
if(fieldName == 'Label'){
MetadataLabel = (String)fieldsToValue.get(fieldName);
} else if(fieldName == 'DeveloperName'){
MetadataDevName = (String)fieldsToValue.get(fieldName);
} else if(fieldName != 'Id' && fieldName != 'Language' && fieldName != 'MasterLabel' && fieldName != 'NamespacePrefix' && fieldName != 'QualifiedApiName') {
// Populating Map for Processing later
metadataFieldValueMap.put(fieldName, fieldsToValue.get(fieldName));
//System.debug('Adding::' + fieldName + ' = ' + fieldsToValue.get(fieldName));
}
}
System.debug('Label is ' + MetadataLabel + '& DeveloperName is ' + MetadataDevName);
// Making sure to have either Label or Developer Name for the CMD record to process
if(String.isBlank(MetadataDevName) && String.isBlank(MetadataLabel)){
throw createCustomException('Make sure to add "Label" attribute in assignemnt for Create and "DeveloperName" for update.');
} else {
//if MetadataDevName available, which means the record exists already - Processing UPDATE
if(!String.isBlank(MetadataDevName)){
UpdateCMD.updateCustomMetadata(String.valueof(obj.getSObjectType()),MetadataDevName, MetadataLabel,metadataFieldValueMap);
} else { // Creating a new Custom Metadata record
//if ID not available - CREATE
UpdateCMD.createCustomMetadata(String.valueof(obj.getSObjectType()), MetadataLabel, metadataFieldValueMap);
}
}
} else {
throw createCustomException('The Object is not a custom metadata');
}
// END
}
}
}
/* Custom Metadata Deploy Methods */
/* ============================================================*/
//Inteface method
public void handleResult(Metadata.DeployResult result, Metadata.DeployCallbackContext context) {
if (result.status == Metadata.DeployStatus.Succeeded) {
//Success
System.debug('Success Result-' + result);
} else {
//Failed
System.debug('Failed Result-' + result);
throw createCustomException(String.valueof(result));
}
}
//Create Custom Metadata record
public static void createCustomMetadata(String metdataName, String label, Map<String, Object> metadataFieldValueMap){
String recordDevName = label.replaceAll(' ', '_');
Metadata.CustomMetadata cMetadata = new Metadata.CustomMetadata();
cMetadata.fullName = metdataName + '.' + recordDevName;
cMetadata.label = label;
for(String key : metadataFieldValueMap.keySet()){
Metadata.CustomMetadataValue cMetadataValue = new Metadata.CustomMetadataValue();
cMetadataValue.Field = key;
cMetadataValue.Value = metadataFieldValueMap.get(key);
//System.debug('Adding Val::' + key + ' = ' + metadataFieldValueMap.get(key));
cMetadata.values.add(cMetadataValue);
}
Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
mdContainer.addMetadata(cMetadata);
UpdateCMD callback = new UpdateCMD();
Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, callback);
}
//Update Custom Metadata record
public static void updateCustomMetadata(String metdataName, String recordDevName, String label, Map<String, Object> metadataFieldValueMap){
Metadata.CustomMetadata cMetadata = new Metadata.CustomMetadata();
cMetadata.fullName = metdataName + '.' + recordDevName;
cMetadata.label = label;
// Getting the metadata details for field type mapping for picklist
// https://help.salesforce.com/articleView?id=000320083&type=1&mode=1
String objType=metdataName;
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Schema.SObjectType leadSchema = schemaMap.get(objType);
Map<String, Schema.SObjectField> fieldMap = leadSchema.getDescribe().fields.getMap();
for(String key : metadataFieldValueMap.keySet()){
Metadata.CustomMetadataValue cMetadataValue = new Metadata.CustomMetadataValue();
cMetadataValue.Field = key;
// Checking if the field type is picklist, then add STRING.VALUEOF()
// https://help.salesforce.com/articleView?id=000320083&type=1&mode=1
if(fieldMap.get(key).getDescribe().getType() == Schema.DisplayType.Picklist) {
cMetadataValue.Value = String.valueof(metadataFieldValueMap.get(key));
} else {
cMetadataValue.Value = metadataFieldValueMap.get(key);
}
//System.debug('Adding Val::' + key + ' = ' + metadataFieldValueMap.get(key));
cMetadata.values.add(cMetadataValue);
}
Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
mdContainer.addMetadata(cMetadata);
UpdateCMD callback = new UpdateCMD();
Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, callback);
}
/* Flow Exception Handling */
/* ============================================================*/
public class CustomException extends Exception {}
static CustomException createCustomException(String message) {
CustomException ex = new CustomException(message);
ex.setMessage(message);
return ex;
}
}