1

Had an issue getting Default value of a Custom object field (Picklist) automatically when the object is instantiated in controller class. Below worked for me.

InstantiatedObject.Field = (Type_of_Field) ObjectType.Field.getDescribe().getDefaultValue();

Do we have any better alternative to get default values in controller method/class?

2 Answers 2

2

There's a new method you can use while creating a record in memory, using a new two-parameter version of newSobject:

Account record = (Account)Account.SObjectType.newSobject(null, true);

The null value is the record type to use, and true specifies that all default field values should be populated.

This method is significantly faster than checking every field on an object to see if there's a default value to populate.

3
  • Hi @sdfcfox Thanks. But it's giving me below error. Unable to create/update fields: IsDeleted. Please check the security settings of this field and verify that it is read/write for your profile or permission set. An unexpected error has occurred. Your development organization has been notified. which seems weird. In security settings there seems no such fields as IsDeleted. This is used within SF instance and by standard user. Therefore I believe there is no need to set special permissions as such.. Nov 21, 2016 at 23:32
  • 1
    @PasanEeriyagama That must be something else in your code; I tried this in my developer org and it worked as documented. There is a "hidden" field called IsDeleted, but it should never be set by code, as the system enforces the integrity of the field. It might be worth investigating as a separate question.
    – sfdcfox
    Nov 22, 2016 at 1:29
  • @sdfcfox I tried with a custom object with no special coding. When I just initialised object by new CustomObject(); it works fine, when I used above, it caused the exception and it wasn't captured by try catch block too. Thanks for the help on this. Nov 22, 2016 at 3:11
1

If you are doing DML into database and want the picklist field value to be default, you can simply leave it unset. It will automatically be setup as the default value.

If you use it for other purpose, I guess you need to go through the getDescribe() way.

1
  • Thanks Lance, It's needed to show on screen, therefore need it populated as we create new object. Nov 21, 2016 at 23:36

You must log in to answer this question.

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