3

When I try the following:

Object defaultValue = MyObject__c.MyField__c.getDescribe().getDefaultValue();
Object defaultValue = MyObject__c.SObject.MyField__c.getDescribe().getDefaultValue();

I always get NULL in the result. Why?

3
  • 1
    may be you are looking for getDefaultValueFormula() ?
    – Ratan Paul
    Mar 14, 2016 at 13:23
  • @Ratan getDefaultValueFormula() doesn't work either.
    – Andrew
    Mar 14, 2016 at 13:26
  • 1
    You don't mention the type of the fields but FYI success.salesforce.com/issues_view?id=a1p300000008XL8AAM; using the latest API version would probably be necessary too if this is the issue.
    – Keith C
    Mar 14, 2016 at 13:47

1 Answer 1

9

Here is an easy way to get default values for all fields on an SObject

Foo__c f = (Foo__c)Foo__c.sObjectType.newSObject(null, true);
  • The first argument to newSObject(..) is the recordType Id
  • The second argument, when true, says to create the sobject with defaultValues

Then, you can use methods like

f.get(Foo__c.MyField__c);  // or ...
f.get(some variable of type SobjectField);  // or ...
f.get('MyField__c');

to get the specific default value for a given field

Remember that default values can be formula-based using $User, $Label, $Profile, ... so based on context, the values may vary

1
  • 2
    You can cast it to a Foo__c record and then do a direct get that does not require casting (e.g. (Foo__c)f.MyField__c instead of (String)f.get('MyField__c')).
    – Adrian Larson
    Mar 15, 2016 at 0:55

You must log in to answer this question.

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