23

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?

25

New feature coming in the next release:

Foo__c f = Foo__c.sobjecttype.newSObject(
  recordTypeId, // can be null
  true); // loadDefaultValues
  • So for now the answer is 'no' - default values aren't actually set when an object is created through apex? – Ryan Elkins Sep 2 '12 at 18:50
6

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.

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.