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
RoadieRoadie 

Pull Default Field Value Using Metadata

Hi, I'm attempting to pull the default value of a field (picklist) out using a metadata call. A simple example of what isn't working is below. The debug statement yields "null." This code works fine if one is trying to find the Label on the field or some other attributes of the field, but not the default value (and, I verified that the default value is set for this picklist named 'Type' on the account object).

 

Code:
Account a = new Account();
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Type;
f = f.getSObjectField().getDescribe();
System.debug('Default Value is: ' + f.getDefaultValue());

Thank you!
 

HarmpieHarmpie
I think it should be something like this:
 
Code:
 Schema.DescribeFieldResult f = Account.Type.getDescribe();
 String defValue = '';
 for(Schema.PicklistEntry pe : f.getPicklistValues()) {
  System.Debug('PE'+pe);
  if(pe.isDefaultValue()) {
   defValue =  pe.getLabel();
  }
 }
 System.Debug('Default = '+defValue);

 
Problem is that when I tested this, none of the picklist values was set to True as default, allthough I did mark 1 as default. System.Debug('PE'+pe), displays the correct values, but my default value still has IsDefaultValue set to false.... Bug?


Message Edited by Harmpie on 12-06-2008 06:51 AM
RoadieRoadie
It sure is looking like a bug. Anyone else?
Abhinav GuptaAbhinav Gupta

Hey Roadie, 

 

Getting Default value  like this will not work for sure, I would suggest you try reloading/loading the sobjects for which you want default values. 

 

 

So if you are inserting new objects, you might need to reload them to see the default value. Even directly without using the describe call.

 

 

Here is a post that explains this : http://www.tgerm.com/2010/01/salesforce-apex-default-values.html