How to create Hierarchy custom settings in Apex

You can use either of the two following constructs:

insert new custSettings__c(SetupOwnerId=UserInfo.getOrganizationId(), SomeField__c='Some Value');

Or:

custSettings__c settings = custSettings__c.getOrgDefaults();
settings.SomeField__c = 'Some Value';
upsert settings custSettings__c.Id;

Either way, basically you need to make sure SetupOwnerId is set to the organization's ID.


To do this with a hierarchy you have to change the 'SetupOwnerId' so the entry recognizes the User or Profile to apply the setting to. As a best practice I like to put the label in parenthesis in the name because when you create one through the Salesforce UI itself it will label the type that way by default.

For a specific user:

    User user1 = TestDataFactory.createUser('Mickey', 'Mouse', Constants.SYSTEM_ADMINISTRATOR, Constants.SYSTEM_ADMINISTRATOR, true);
    //^^ this creates the test user and inserts them into the database temporarily^^
    CustomSettingName__c setting = new CustomSettingName__c();
    setting.Name = 'CustomSettingName (User)';
    //^^ Name input + hierarchy type^^
    setting.CustomSettingFieldName__c = false;
    setting.SetupOwnerId = user1.id;
    //^^ this line tells the setting which user it applies to^^
    insert setting;

For a specific profile:

    User user1 = TestDataFactory.createUser('Mickey', 'Mouse', Constants.SYSTEM_ADMINISTRATOR, Constants.SYSTEM_ADMINISTRATOR, true);
    //^^ this creates the test user and inserts them into the database temporarily^^
    CustomSettingName__c setting = new CustomSettingName__c();
    setting.Name = 'CustomSettingName (Profile)';
    //^^ Name input + hierarchy type^^
    setting.CustomSettingFieldName__c = false;
    setting.SetupOwnerId = user1.ProfileId;
    //^^ this line tells the setting which profile it applies to^^
    insert setting;

Hope this helps!