How to use Custom Setting in Apex Salesforce

by Rijwan Mohmmed
How to use Custom Setting in Apex Salesforce

Custom Setting in Salesforce is the same as a custom object.
We can retrieve custom setting data without soql so its also helpful for minimizing soql query.

There is two types of Custom settings:

  1. List Custom Setting : It used ti store static data and can be used across the Salesforce Org. Data cannot be varied at the profile or user level but will be available for OWD.
  2. Hierarchy Custom Settings : It store the data that you may personalize for the profile, user and owd level.

How to create Custom Settings :

Setup -> Develop -> Custom Settings -> New -> 
Lable => 'Enviroment'
Object ==> 'Enviroment'
Click Save

Create 1 Text field for Username.

Create Custom Setting Records :

1. Name ==> Sandbox     Username ==> SalesforceSandbox@g.com
2. Name ==> Production     Username ==> SalesforceProduction@g.com

Retrieve List Custom Setting:

  1. Retrieve all records of a particular custom setting :
public class TechdicerCustomSettings {

	public TechdicerCustomSettings(){
	   // retrive all records of a particular  custom setting
	   List<myCusttomSettingName__c> cusList = myCusttomSettingName__c.getAll().values();

           System.debug(cusList[0].Username__c);

	}
	
}

myCusttomSettingName__c ==> API Name of Custom Setting

2. Retrieve a record of a particular custom setting :

public class TechdicerCustomSettings {

	public TechdicerCustomSettings(){
	   // retrive a record of a particular  custom setting
	   myCusttomSettingName__c obj = myCusttomSettingName__c.getInstance('Sandbox');

           System.debug(obj[0].Username__c);

	}
	
}

myCusttomSettingName__c ==> API Name of Custom Setting
Sandbox ==> Name of Record

3. Retrieve all records of a particular custom setting in Map :

public class TechdicerCustomSettings {

	public TechdicerCustomSettings(){
	   // retrieve  all records of a particular  custom setting in Map
	   Map<String, myCusttomSettingName__c> mcs = myCusttomSettingName__c.getAll();
	}
	
}

Hierarchy Custom Settings : Get Hierarchy Custom Settings value for the profile specified with ProfileId

GamesSupport__c mhc = GamesSupport__c.getInstance(ProfileId);
string mPhone = mhc.Corporate_number__c;
// return the data  for the organization using getOrgDefaults
Hierarchy__c CS = Hierarchy__c.getOrgDefaults();

What’s your Reaction?
+1
3
+1
1
+1
1
+1
0
+1
6
+1
0

You may also like

2 comments

Swapnil Ahire September 21, 2023 - 10:22 am

Hi Rijwan,
Your blogs are very useful for learning the concepts and very easy to understand.
Thanks.

Reply
Rijwan Mohmmed October 3, 2023 - 3:24 pm

Thanks

Reply

Leave a Comment