3

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

2 Answers 2

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,',');
}
3
  • Thank you! But I made a little mistake - I need field labels, not field names. Aug 31, 2019 at 17:46
  • You can get label instead of name - fields.add(fld.getDescribe().getLabel()); Aug 31, 2019 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, 2019 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).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .