1

I have a custom metadata type in which I want to add the API names of some custom fields to use the values in a Dynamic Soql. I used a list to get the values of the custom metadata fields. Is there a simple way to put the values of the list in a comma separated string to use this in a dynamic Soql. With for example a .get or describe?

Field

A__c = Test1__c
B__c = Test2__c
C__c = Test3__c

For example:

List<CustomMetadata__mdt> cFieldsValues = [SELECT A__c, B__c, C__c FROM CustomMetadata__mdt];

String soqlstring = '';
for (Integer x = 0; x < cFieldsValues.size(); x++){
    soqlstring += cFieldsValues[x].get;
}
Result
soqlstring='Test1__c,Test2__c,Test3__c';
4

When You say

I used a list to get the values of the custom metadata fields.

First of all, You should consider that [SELECT A__c, B__c, C__c FROM CustomMetadata__mdt] SOQL returns you a list of CMT records, not fields. So if You want to get a concrete record of CMT you should specify filter conditions [SELECT A__c, B__c, C__c FROM CustomMetadata__mdt WHERE DeveloperName = 'CMTRecordName']

Assume You have one single record of CustomMetadata__mdt and the type of the queried CMT fields is String and you want to dynamically collect the values of the fields. Then you can use getPopulatedFieldsAsMap() method which returns a map of populated field names and their corresponding values:

CustomMetadata__mdt record = [
    SELECT 
        A__c, 
        B__c, 
        C__c /*, D__c, ..., N__c */ 
    FROM custommetadata 
    WHERE DeveloperName = 'CMTRecordName'
];
Map<String, Object> populatedFieldsAsMap = record.getPopulatedFieldsAsMap(); 
populatedFieldsAsMap.keySet().remove('Id'); /* Id field is queried by default */
String soqlstring = String.join(populatedFieldsAsMap.values(), ',');
/* soqlstring = 'Test1__c,Test2__c,Test3__c'  */

Generally, You can use String.join() method to join the elements of the specified iterable object, such as a List, into a single string separated by the specified separator.

For instance:

List<String> simpleList = new List<String>{'Test1__c', 'Test2__c', 'Test3__c'};
String soqlstring = String.join(simpleList, ',');
/* soqlstring = 'Test1__c,Test2__c,Test3__c'  */
|improve this answer|||||
  • Thanks for the explanation it was very concise. – Thomas Dec 4 '19 at 4:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.