[SalesForce] Use Custom Metadata as lookup instead of hard coding

I've now read so many articles on Custom Metadata my head is spinning. Can someone give me a simple answer please as to how to use this instead of hardcoding a check for a value?

  1. I have a custom field on Account that holds an AccountGroup value
  2. I need to update a value on Accounts based on which AccountGroup it falls into

eg.

If account.accountgroup = 'ABC' then field = 'x'
else if account.accountgroup = 'DEF' then field = 'y'

I would like to replace the hardcoded 'ABC' and 'DEF' with (what I believe is better) a metadata lookup.

I created a Custom Metadata Type with 2 fields, with example values in them:

GroupCode: 'ABC'
GroupType: 'Primary'

Am I doing it correctly, and how will I go about using this Custom Metadata Type in my apex code trigger query above?

Best Answer

Yes, you're doing it right. Your code would look approximately like this:

for(Account record: Trigger.new) {
  AccountGroup__mdt[] value = [select GroupType__c FROM AccountGroup__mdt WHERE GroupCode__c = :record.AccountGroup__c];
  if(!value.isEmpty()) {
    record.Field__c = value[0].GroupType__c;
  }
}

Note that this is one of the few times where a SOQL in a loop is acceptable. It does not consume governor limits like a normal query does.

Edit: As a minor performance optimization, you might still consider using the normal aggregate-query-update pattern, for consistency:

Map<String, String> codeToType = new Map<String, String>();
for(Account record: Trigger.new) {
  codeToType.put(record.AccountGroup__c, null);
}
for(AccountGroup__mdt record: [SELECT GroupCode__c, GroupType__c FROM AccountGroup__mdt FROM AccountGroup__mdt WHERE GroupCode__c = :codeToType.keySet()]) {
  codeToType.put(record.GroupCode__c, record.GroupType__c);
}
for(Account record: Trigger.new) {
  record.Field__c = codeToType.get(record.AccountGroup__c);
}

I recommend this pattern because it is mildly more efficient CPU-wise to do so, even when other limits are essentially free.

Related Topic