function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Spencer EdieSpencer Edie 

How to get formula content of formula field

If I have a formula field whose formula is "= TODAY() - Account.Last_Contact_Date__c", is there a way for me to use apex/soql to access that field such that it returns the formula as a string rather than the date it would otherwise return?
Best Answer chosen by Spencer Edie
Alain CabonAlain Cabon
Hi,
 
String selectedObject = Account.sObjectType.getDescribe().getName();

selectedObject = 'MyObject__c';

system.debug(selectedObject);

Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Schema.SObjectType objectSchema = schemaMap.get(selectedObject);
Map<String, Schema.SObjectField> fieldMap = objectSchema.getDescribe().fields.getMap();
for (String fieldName: fieldMap.keySet()){  
    Schema.DescribeFieldResult df  =  fieldMap.get(fieldName).getDescribe();
    if (df.isCalculated() &&  df.getCalculatedFormula() != null) {
         system.debug('field name:' +  fieldName + ' label:' + df.getLabel() + 
        ' type:' +  df.getType() + ' formula:' + df.getCalculatedFormula().replace('\n',' ').replace('\r',' '));
    }  
}


https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_fields_describe.htm