2

I have custom object ExchangeRate__c. How to get all fields, which have data type "currency" and put their field names in a string?

3

You can use below method and pass the object name ExchangeRate__c as parameter:

public static String getCurrencyFields(String obj) {
    List<String> fields = new List<String>();
    SObjectType objType = Schema.getGlobalDescribe().get(obj);
    Map<String,Schema.SObjectField> mfieldsMap = objType.getDescribe().fields.getMap();

    for(Schema.SObjectField fld : mfieldsMap.values()) {
        if(fld.getDescribe().getType()==Schema.DisplayType.CURRENCY){
            fields.add(fld.getDescribe().getName());
        }
    }
    return String.join(fields,',');
}
| improve this answer | |
  • Thank you! But I made a little mistake - I need field labels, not field names. – LostSoul325 Aug 31 '19 at 17:46
  • You can get label instead of name - fields.add(fld.getDescribe().getLabel()); – salesforce-sas Aug 31 '19 at 17:51
  • 2
    Improvement suggestion - pass in SObjectType rather than String as that is more typesafe and avoid the lookup into GlobalDescribe. You can also get the sobjectType from string more efficiently using: Type t = Type.forName(name); SobjectType sobjType = ((SObject)t.newInstance()).getSObjectType(); – cropredy Sep 1 '19 at 2:41
3

You wouldn't use a query for this, but rather the DescribeSObjectResult and DescribeFieldResult classes.

Schema.SObjectType.<Sobject API Name>.fields gives you a Map<String, Schema.SObjectField> containing the field tokens for all of the fields on the object

You can then iterate over those Schema.SObjectField instances, and get the DescribeFieldResult from them using the getDescribe() method.

The DescribeFieldResult class gives you access to the metadata of the field, including what type of field it is (the getType() method).

| improve this answer | |

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.