1

I have custom fields on my Account object. Some of them have default value, let say "Days__c" as number with default value 0.

When I insert the object like this:

Account account = new Account(Name = 'AccountName');
insert account;

Is there a way for me to do

account.Days__c 

to get the default value 0 without querying once again with the required field ? After an insert the Id field is available

account.Id

and I want to do it as well with other fields.

Any ideas ? Thank you.

  • 1
    No? You will have to query. Or you could simply add the field when creating the account and set it to 0 since you know it defaults to 0. If you need it later just check for null and set it to 0. Lots of ways to do it depending on what your goal is – Eric Dec 13 '16 at 8:39
1

You can get all the default values in one go if you use the SObjectType.newSObject method with the signature:

public sObject newSObject(ID recordTypeId, Boolean loadDefaults)

And since they released the getPopulatedFieldsAsMap method, you can now achieve what you want with just one line. As a generic example, run the following in Execute Anonymous:

static Map<String, Object> getDefaultFieldsAsMap(SObjectType s, Id recordTypeId)
{
    return s.newSObject(recordTypeId, true).getPopulatedFieldsAsMap();
}
static Map<String, Object> getDefaultFieldsAsMap(SObjectType s)
{
    return getDefaultFieldsAsMap(s, null);
}

system.debug(getDefaultFieldsAsMap(Account.sObjectType));

You can easily drop these methods into a utility class if you want to reuse them elsewhere.

| improve this answer | |
  • Thank you. Very helpful. Any idea why this is not working: System.debug( Invoice__c.getSObjectType().newSObject('a0A9E0000001PU2UAM', true).getPopulatedFieldsAsMap().get('Name') ); With the error: Error on line 2, column 1: System.SObjectException: Record Type is Unavailable – Simonp Dec 14 '16 at 10:42
  • The key prefix for RecordType Id values is 012. You must use the Id of the RecordType you want to load default values for. a0A is a custom object prefix. Also, make sure the RecordType you select is active. I was able to reproduce this error by deactivating a RecordType or using one set up for a different SObject. @SimonPlacentino – Adrian Larson Dec 14 '16 at 15:11
3

The DescribeFieldResult class has methods that supply the default values but there are bugs. But for a few fields of types not subject to those bugs you could assign the default value using something like:

account.Days__c = (Decimal) Account.Days__c.getDescribe.getDefaultValue();
| 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.