Find your content:

Search form

You are here

Does 'default value' do anything if the object is created through Apex?

 
Share

I created a currency field on OpportunityLineItem that has a default value set to 0.00. In my test method I create a record and insert it. I then query it back out and try to assert that the field is equal to 0. It keeps coming back as null, however.

Does 'default value' only relate to objects created through the UI? Am I doing something wrong?

If I want to set a default value on a field do I need to do this through a trigger?


Attribution to: Ryan Elkins

Possible Suggestion/Solution #1

Yes, this is possible. You'll just need to construct the OpportunityLineItem from it's sObject type and you'll start with your custom currency field populated.

OpportunityLineItem line = 
  (OpportunityLineItem) OpportunityLineItem.sobjecttype.newSObject(
    recordTypeId, // optionally set a record type
    true); // loadDefaultValues

There are lot more details on it in the usages tips are from the docs

  • For required fields that have no default values, make sure to provide a value before inserting the new sObject. Otherwise, the insertion results in an error. An example is the Account Name field or a master-detail relationship field.
  • Since picklists and multi-select picklists can have default values specified per record type, this method populates the default value corresponding to the record type specified.
  • If fields have no predefined default values and the loadDefaults argument is true, this method creates the sObject with field values of null.
  • If the loadDefaults argument is false, this method creates the sObject with field values of null.
  • This method populates read-only custom fields of the new sObject with default values. You can then insert the new sObject with the read-only fields, even though these fields cannot be edited after they’re inserted.
  • If a custom field is marked as unique and also provides a default value, inserting more than one new sObject will cause a run-time exception because of duplicate field values.

Attribution to: Ralph Callaway

Possible Suggestion/Solution #2

New feature coming in the next release:

Foo__c f = Foo__c.sobjecttype.newSObject(
  recordTypeId, // can be null
  true); // loadDefaultValues

Attribution to: Rich Unger
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/1025

My Block Status

My Block Content