I'm trying to populate/set/put/initialize a custom setting's field with a calculated value within my apex code. The field type is number. Is there a way to do this?

1 Answer 1


For Hierarchy custom settings, you can get an instance, then populate and insert it:

//fetches or creates a Custom Setting at the organization level 
HierarchySetting__c setting = HierarchySetting__c.getOrgDefaults();
setting.CustomField__c = 'http://salesforce.stackexchange.com/';
upsert setting;

Note the use of upsert

Or with List custom settings: new one up with the fields and insert:

upsert new ListSetting__c(
    Name = 'sandbox',
    CustomField__c = 'https://test.salesforce.com/'

upsert new ListSetting__c(
    Name = 'production',
    CustomField__c = 'https://login.salesforce.com/'

Check out the docs:

  • Can you clarify something for me? In the hierarchical custom settings, why are users without the customize application privilege able to upsert the custom setting, when that privilege seems to be required? help.salesforce.com/apex/… Jun 2, 2014 at 18:46
  • Apex doesn't enforce CRUD security or FLS unless you're in execute anonymous context. So this code runs alright regardless of the user's privileges. @nivyaj Jun 2, 2014 at 21:43

You must log in to answer this question.

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