Retrieve the formulas from the Salesforce Formula fields

1.5k Views Asked by At

I am looking for a way to get the formulas from Salesforce Formula fields. We are using the CDATA Drivers to connect to Salesforce. But I am not seeing any option to retrieve the Salesforce formulas.

2

There are 2 best solutions below

1
eyescream On

No idea what "cdata drivers" are so hopefully some of these will point you in right direction.

In Apex you can use "describe" calls. If all other options fail - you could build a custom service that returns this data to you.

Schema.DescribeFieldResult dfr = Account.Address__c.getDescribe();
System.debug(dfr.getCalculatedFormula());
// BillingStreet & BR() & BillingCity & BR() &  BillingPostalCode & BR() &  BillingCountry & BR() &  Street2__c & BR() & Street3__c

You've tagged metadata API so if you really use that - similar info should be available in it.

<CustomField>
    <fullName>Address__c</fullName>
    <externalId>false</externalId>
    <formula>BillingStreet &amp; BR() &amp; BillingCity &amp; BR() &amp;  BillingPostalCode &amp; BR() &amp;  BillingCountry &amp; BR() &amp;  Street2__c &amp; BR() &amp; Street3__c</formula>
    <formulaTreatBlanksAs>BlankAsZero</formulaTreatBlanksAs>
    <label>Address</label>
    <required>false</required>
    <trackHistory>false</trackHistory>
    <type>Text</type>
    <unique>false</unique>
</CustomField>

In REST API it's similar, a call to /services/data/v48.0/sobjects/Account/describe will return (among others)

{
    "aggregatable" : true,
    "aiPredictionField" : false,
    "autoNumber" : false,
    "byteLength" : 3900,
    "calculated" : true,
    "calculatedFormula" : "BillingStreet & BR() & BillingCity & BR() &  BillingPostalCode & BR() &  BillingCountry & BR() &  Street2__c & BR() & Street3__c",
    "cascadeDelete" : false,
    (...)
    "formulaTreatNullNumberAsZero" : true,
    "groupable" : false,
    "highScaleNumber" : false,
    "htmlFormatted" : true,
    "idLookup" : false,
    "inlineHelpText" : null,
    "label" : "Address",
    "length" : 1300,
    "mask" : null,
    "maskType" : null,
    "name" : "Address__c",
    (...)
    "type" : "string",
    "unique" : false,
    "updateable" : false,
    "writeRequiresMasterRead" : false
  }

And finally there's Tooling API where you can query the metadata like you'd query normal database tables. But the core of what you need will be hidden in a JSON field you'd have to parse. If your tool is some ETL - check if it can query FieldDefinition table.

/services/data/v48.0/tooling/query?q=SELECT+Metadata+FROM+FieldDefinition+WHERE+EntityDefinitionId+=+'Account'+AND+QualifiedApiName+=+'Address__c'

0
Lorela S. On

CData Salesforce driver exposes a view called: 'Formulas' which you can query to get the available formula definition. Documentation: https://cdn.cdata.com/help/RFJ/jdbc/pg_table-formulas.htm