Custom Setting in Salesforce is similar to a custom object. It enables the developer to create a custom set of data and apex classes, formula field, flows, can use this data. Custom Setting data are stored in the cache. For Custom Settings, there is no need to use SOQL queries that counts against Governor Limits.
Few Reasons to use Custom Settings-
- Custom Setting data are exposed in the application cache.
- We can access Custom Setting without SOQL.
Types of Custom Setting:
- List Custom Setting: List Custom Settings are used to store the reusable static set of data that is accessible across your organization. In List Custom Setting the data does not vary with profile or user.
From Salesforce Spring 18 release – list custom settings option is grayed out. However, we can simply enable it.
Go to Setup->Data Management->Schema Settings and Enable “Manage List Custom Settings Type”
- Hierarchy Custom Setting: Hierarchy Custom Settings lets you “personalize” settings for specific profiles or users. In this, we can have different values at the organization level, profile level, user level.
How to Create Custom settings:
Setup -> Develop -> Custom Settings -> New -> For Label “Country Code” and for Object “Country_Code” and Save.
After you define custom settings, add fields to them. The custom fields contain the data used by the custom setting.
After creating a custom setting and adding fields, you can add records, then use the values in these records in your Apex code and validation rules. To create records –
- Select Custom Settings, and then click Manage next to a custom setting. Or from the detail page for a custom setting, click Manage.
- Click New or Edit next to an existing data set. Add or change data.
Accessing a List Custom Setting: –
- getValues(Custom_Setting_Name) method returns the instance of the Custom Setting.
If we know the name of Custom Setting. Name like ‘Canada’ then we can use the getValues() method.
Custom_Setting_Name__c record = Custom_Setting_Name__c.getValues(data_set_name);
- Values() method returns a list of All custom setting records.
List<Custom_Setting_Name__c> customList = Custom_Setting_Name__c.getAll().values();
Accessing a Hierarchy Custom Setting: –
- getOrgDefaults() method return the dataset values for the organization level.
Custom_Setting_Name__c cs = Custom_Setting_Name__c.getOrgDefaults();
- getInstance() method return the data set values for the specified profile or user.
Custom_Setting_Name__c cs = Custom_Setting_Name__c.getInstance(Profile_ID);
Custom_Setting_Name__c cs = Custom_Setting_Name__c.getInstance(User_ID);