I have 10 custom settings in my org . I need to fetch all and need to use in apex class
- 3Have you read the relevant documentation and examples? What specific issue are you encountering?David Reed– David Reed2018-03-27 11:43:21 +00:00Commented Mar 27, 2018 at 11:43
- Hi David, Thanks for update, I have checked doc and found only single custom settings to fetch . Iam looking for list of custom settings need to be displayed in a vf pageBhanu Prakash Reddy– Bhanu Prakash Reddy2018-03-27 12:08:15 +00:00Commented Mar 27, 2018 at 12:08
- 2Please clarify the question: Do you need all values for a given custom setting, or do you need all the custom settings AND their values? What is your use-case for not knowing the names of all the custom settings you need to iterate over in an org? Or are you saying that you know the names of the ten custom settings and you want to fetch all 10 by name and use them in an Apex class?DavidSchach– DavidSchach2018-03-27 16:21:11 +00:00Commented Mar 27, 2018 at 16:21
2 Answers
There is no decent way to do it, but can be achieved using a describe call.
Describe call result has a method that indicates whether it is an SObjectType or a normal SObject or a Custom Setting. We can take advantage of that to query all custom settings values.
Algorithm goes like:
-
- Do Global Describe to get Whole Org's Metadata
- Iterate on individual Object and check if its a CustomSetting or not
- If Custom Setting, Using describe call on that object and get all fields of that object
- Create Dynamic SOQL and query the custom settings record back.
Below code snippet will help you.
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe(); for(String objectName :gd.keySet()){ Schema.SObjectType result=gd.get(objectName); if(result.getDescribe().isCustomSetting()){ System.debug(objectName); String query = 'SELECT'; // Grab the fields from the describe method and append them to the queryString one by one. Map<String, Schema.SObjectField> objectFields =result.getDescribe().fields.getMap(); for(String s : objectFields.keySet()) { query += ' ' + s + ','; } if (query.subString(query.Length()-1,query.Length()) == ','){ query = query.subString(0,query.Length()-1); } // Add FROM statement query += ' FROM ' + objectName; //System.debug(query ); //Show Querry if you want System.debug(Database.query(query ));//Query and Display Sobject or show on VP } } You can obtain all records of a List custom setting by doing
Map<String, CustomSetting__c> settings = CustomSetting__c.getAll(); This provides a map of the setting's Name to its value. You can get a flat list by doing
CustomSetting__c.getAll().values() where CustomSetting__c is the name of your custom setting object. This applies for List-type custom settings; for Hierarchy custom settings, which don't have a required Name field, you would simply run a SOQL query against the object:
SELECT FIELDS_DESIRED FROM CustomSetting__c