Populating Custom Settings field using Apex

  • 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?

  • 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? https://help.salesforce.com/apex/HTViewHelpDoc?id=cs_about.htm&language=en_US

    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

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM