anusha(salesforce developer)

Saturday, 16 July 2016

Custom Settings Methods

Custom settings are similar to custom objects and enable application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user. All custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database. This data can then be used by formula fields, validation rules, flows, Apex, and the SOAP API.
There are two types of custom settings:
List Custom Settings
A type of custom setting that provides a reusable set of static data that can be accessed across your organization. If you use a particular set of data frequently within your application, putting that data in a list custom setting streamlines access to it. Data in list settings does not vary with profile or user, but is available organization-wide. Examples of list data include two-letter state abbreviations, international dialing prefixes, and catalog numbers for products. Because the data is cached, access is low-cost and efficient: you don't have to use SOQL queries that count against your governor limits.
Hierarchy Custom Settings
A type of custom setting that uses a built-in hierarchical logic that lets you “personalize” settings for specific profiles or users. The hierarchy logic checks the organization, profile, and user settings for the current user and returns the most specific, or “lowest,” value. In the hierarchy, settings for an organization are overridden by profile settings, which, in turn, are overridden by user settings.
The following examples illustrate how you can use custom settings:
  • A shipping application requires users to fill in the country codes for international deliveries. By creating a list setting of all country codes, users have quick access to this data without needing to query the database.
  • An application displays a map of account locations, the best route to take, and traffic conditions. This information is useful for sales reps, but account executives only want to see account locations. By creating a hierarchy setting with custom checkbox fields for route and traffic, you can enable this data for just the “Sales Rep” profile.
You can create a custom setting in the Salesforce user interface: from Setup, enter Custom Settings in the Quick Find box, then select Custom Settings. After creating a custom setting and you’ve added fields, provide data to your custom setting by clicking Manage from the detail page. Each data set is identified by the name you give it.
For example, if you have a custom setting named Foundation_Countries__c with one text field Country_Code__c, your data sets can look like the following:
Data Set NameCountry Code Field Value
United StatesUSA
CanadaCAN
United KingdomGBR

You can also include a custom setting in a package. The visibility of the custom setting in the package depends on theVisibility setting.

Usage of Custom setting

Custom settings methods are all instance methods, that is, they are called by and operate on a particular instance of a custom setting. There are two types of custom settings: hierarchy and list. The methods are divided into those that work with list custom settings, and those that work with hierarchy custom settings.
For more information on creating custom settings in the Salesforce user interface, see “Custom Settings” in the Salesforce online help.

Custom Setting Examples

The following example uses a list custom setting called Games. Games has a field called GameType. This example determines if the value of the first data set is equal to the string PC.
1List<Games__C> mcs = Games__c.getall().values();
2boolean textField = null;
3if (mcs[0].GameType__c == 'PC') {
4  textField = true;
5}
6system.assertEquals(textField, true);
The following example uses a custom setting from Country and State Code Custom Settings Example. This example demonstrates that the getValues and getInstance methods list custom setting return identical values.
1Foundation_Countries__c myCS1 = Foundation_Countries__c.getValues('United States');
2String myCCVal = myCS1.Country_code__c;
3Foundation_Countries__c myCS2 = Foundation_Countries__c.getInstance('United States');
4String myCCInst = myCS2.Country_code__c;
5system.assertEquals(myCCinst, myCCVal);

Accessing a List Custom Setting

The following example returns a map of custom settings data. The getAll method returns values for all custom fields associated with the list setting.
1Map<String_dataset_name, CustomSettingName__c> mcs = CustomSettingName__c.getAll();
The following example uses the getValues method to return all the field values associated with the specified data set. This method can be used with both list and hierarchy custom settings, using different parameters.
1CustomSettingName__c mc = CustomSettingName__c.getValues(data_set_name);

Accessing a Hierarchy Custom Setting

The following example uses the getOrgDefaults method to return the data set values for the organization level:
1CustomSettingName__c mc = CustomSettingName__c.getOrgDefaults();
The following example uses the getInstance method to return the data set values for the specified profile. The getInstancemethod can also be used with a user ID.
1CustomSettingName__c mc = CustomSettingName__c.getInstance(Profile_ID);

Hierarchy Custom Setting Examples

In the following example, the hierarchy custom setting GamesSupport has a field called Corporate_number. The code returns the value for the profile specified with pid.
1GamesSupport__c mhc = GamesSupport__c.getInstance(pid);
2string mPhone = mhc.Corporate_number__c;
The example is identical if you choose to use the getValues method.
The following example shows how to use hierarchy custom settings methods. For getInstance, the example shows how field values that aren't set for a specific user or profile are returned from fields defined at the next lowest level in the hierarchy. The example also shows how to use getOrgDefaults.
Finally, the example demonstrates how getValues returns fields in the custom setting record only for the specific user or profile, and doesn't merge values from other levels of the hierarchy. Instead, getValues returns null for any fields that aren't set. This example uses a hierarchy custom setting called Hierarchy. Hierarchy has two fields: OverrideMe andDontOverrideMe. In addition, a user named Robert has a System Administrator profile. The organization, profile, and user settings for this example are as follows:
Organization settings
OverrideMe: Hello
DontOverrideMe: World
Profile settings
OverrideMe: Goodbye
DontOverrideMe is not set.
User settings
OverrideMe: Fluffy
DontOverrideMe is not set.
The following example demonstrates the result of the getInstance method if Robert calls it in his organization:
1Hierarchy__c CS = Hierarchy__c.getInstance();
2System.Assert(CS.OverrideMe__c == 'Fluffy');
3System.assert(CS.DontOverrideMe__c == 'World');
If Robert passes his user ID specified by RobertId to getInstance, the results are the same. This is because the lowest level of data in the custom setting is specified at the user level.
1Hierarchy__c CS = Hierarchy__c.getInstance(RobertId);
2System.Assert(CS.OverrideMe__c == 'Fluffy');
3System.assert(CS.DontOverrideMe__c == 'World');
If Robert passes the System Administrator profile ID specified by SysAdminID to getInstance, the result is different. The data specified for the profile is returned:
1Hierarchy__c CS = Hierarchy__c.getInstance(SysAdminID);
2System.Assert(CS.OverrideMe__c == 'Goodbye');
3System.assert(CS.DontOverrideMe__c == 'World');
When Robert tries to return the data set for the organization using getOrgDefaults, the result is:
1Hierarchy__c CS = Hierarchy__c.getOrgDefaults();
2System.Assert(CS.OverrideMe__c == 'Hello');
3System.assert(CS.DontOverrideMe__c == 'World');
By using the getValues method, Robert can get the hierarchy custom setting values specific to his user and profile settings. For example, if Robert passes his user ID RobertId to getValues, the result is:
1Hierarchy__c CS = Hierarchy__c.getValues(RobertId);
2System.Assert(CS.OverrideMe__c == 'Fluffy');
3// Note how this value is null, because you are returning
4// data specific for the user
5System.assert(CS.DontOverrideMe__c == null);
If Robert passes his System Administrator profile ID SysAdminID to getValues, the result is:
1Hierarchy__c CS = Hierarchy__c.getValues(SysAdminID);
2System.Assert(CS.OverrideMe__c == 'Goodbye');
3// Note how this value is null, because you are returning
4// data specific for the profile
5System.assert(CS.DontOverrideMe__c == null);

Country and State Code Custom Settings Example

This example illustrates using two custom setting objects for storing related information, and a Visualforce page to display the data in a set of related picklists.
In the following example, country and state codes are stored in two different custom settings: Foundation_Countries and Foundation_States.
The Foundation_Countries custom setting is a list type custom setting and has a single field, Country_Code.
Custom Setting Countries Example
The Foundation_States custom setting is also a List type of custom setting and has the following fields:
  • Country Code
  • State Code
  • State Name
Custom Settings State Example
The Visualforce page shows two picklists: one for country and one for state.
Custom Settings Visualforce Page
01<apex:page controller="CountryStatePicker">
02   <apex:form >
03      <apex:actionFunction name="rerenderStates" rerender="statesSelectList" >
04          <apex:param name="firstParam" assignTo="{!country}" value="" />
05      </apex:actionFunction>
06
07   <table><tbody>
08      <tr>
09        <th>Country</th>
10          <td>
11             <apex:selectList id="country" styleclass="std" size="1"
12                value="{!country}" onChange="rerenderStates(this.value)">
13                    <apex:selectOptions value="{!countriesSelectList}"/>
14             </apex:selectList>
15          </td>
16      </tr>
17      <tr id="state_input">
18        <th>State/Province</th>
19          <td>
20            <apex:selectList id="statesSelectList" styleclass="std" size="1"
21                 value="{!state}">
22                   <apex:selectOptions value="{!statesSelectList}"/>
23            </apex:selectList>
24          </td>
25      </tr>
26   </tbody></table>
27   </apex:form>
28</apex:page>
The Apex controller CountryStatePicker finds the values entered into the custom settings, then returns them to the Visualforce page.
01public with sharing class CountryStatePicker {
02
03// Variables to store country and state selected by user
04    public String state { get; set; }
05    public String country {get; set;}  
06
07    // Generates country dropdown from country settings
08    public List<SelectOption> getCountriesSelectList() {
09        List<SelectOption> options = new List<SelectOption>();
10        options.add(new SelectOption('''-- Select One --'));       
11
12        // Find all the countries in the custom setting
13        Map<StringFoundation_Countries__c> countries = Foundation_Countries__c.getAll();
14         
15        // Sort them by name
16        List<String> countryNames = new List<String>();
17        countryNames.addAll(countries.keySet());
18        countryNames.sort();
19         
20        // Create the Select Options.
21        for (String countryName : countryNames) {
22            Foundation_Countries__c country = countries.get(countryName);
23            options.add(new SelectOption(country.country_code__c, country.Name));
24        }
25        return options;
26    }
27     
28    // To generate the states picklist based on the country selected by user.
29    public List<SelectOption> getStatesSelectList() {
30        List<SelectOption> options = new List<SelectOption>();
31        // Find all the states we have in custom settings.
32        Map<StringFoundation_States__c> allstates = Foundation_States__c.getAll();
33
34        // Filter states that belong to the selected country
35        Map<StringFoundation_States__c> states = new Map<StringFoundation_States__c>();
36        for(Foundation_States__c state : allstates.values()) {
37            if (state.country_code__c == this.country) {
38                states.put(state.name, state);
39            }
40        }
41         
42        // Sort the states based on their names
43        List<String> stateNames = new List<String>();
44        stateNames.addAll(states.keySet());
45        stateNames.sort();
46         
47        // Generate the Select Options based on the final sorted list
48        for (String stateName : stateNames) {
49            Foundation_States__c state = states.get(stateName);
50            options.add(new SelectOption(state.state_code__c, state.state_name__c));
51        }
52         
53        // If no states are found, just say not required in the dropdown.
54        if (options.size() > 0) {
55            options.add(0new SelectOption('''-- Select One --'));
56        else {
57            options.add(new SelectOption('''Not Required'));
58        }
59        return options;
60    }
61}

List Custom Setting Methods

The following are instance methods for list custom settings.

getAll()

Returns a map of the data sets defined for the custom setting.

Signature

public Map<String, CustomSetting__c> getAll()

Return Value

Usage

If no data set is defined, this method returns an empty map.


getInstance(dataSetName)

Returns the custom setting data set record for the specified data set name. This method returns the exact same object asgetValues(dataSetName).

Signature

public CustomSetting__c getInstance(String dataSetName)

Parameters

dataSetName
Type: String

Return Value

Type: CustomSetting__c

Usage

If no data is defined for the specified data set, this method returns null.

getValues(dataSetName)

Returns the custom setting data set record for the specified data set name. This method returns the exact same object asgetInstance(dataSetName).

Signature

public CustomSetting__c getValues(String dataSetName)

Parameters

dataSetName
Type: String

Return Value

Type: CustomSetting__c

Usage

If no data is defined for the specified data set, this method returns null.

Hierarchy Custom Setting Methods

The following are instance methods for hierarchy custom settings.

getInstance()

Returns a custom setting data set record for the current user. The fields returned in the custom setting record are merged based on the lowest level fields that are defined in the hierarchy.

Signature

public CustomSetting__c getInstance()

Return Value

Type: CustomSetting__c

Usage

If no custom setting data is defined for the user, this method returns a new custom setting object. The new custom setting object contains an ID set to null and merged fields from higher in the hierarchy. You can add this new custom setting record for the user by using insert or upsert. If no custom setting data is defined in the hierarchy, the returned custom setting has empty fields, except for the SetupOwnerId field which contains the user ID.

This method is equivalent to a method call to getInstance(User_Id) for the current user.

Example

  • Custom setting data set defined for the user: If you have a custom setting data set defined for the user “Uriel Jones,” for the profile “System Administrator,” and for the organization as a whole, and the user running the code is Uriel Jones, this method returns the custom setting record defined for Uriel Jones.
  • Merged fields: If you have a custom setting data set with fields A and B for the user “Uriel Jones” and for the profile “System Administrator,” and field A is defined for Uriel Jones, field B is null but is defined for the System Adminitrator profile, this method returns the custom setting record for Uriel Jones with field A for Uriel Jones and field B from the System Administrator profile.
  • No custom setting data set record defined for the user: If the current user is “Barbara Mahonie,” who also shares the “System Administrator” profile, but no data is defined for Barbara as a user, this method returns a new custom setting record with the ID set to null and with fields merged based on the fields defined in the lowest level in the hierarchy.

getInstance(userId)

Returns the custom setting data set record for the specified user ID. The lowest level custom setting record and fields are returned. Use this when you want to explicitly retrieve data for the custom setting at the user level.

Signature

public CustomSetting__c getInstance(ID userId)

Parameters

userId
Type: ID

Return Value

Type: CustomSetting__c

Usage

If no custom setting data is defined for the user, this method returns a new custom setting object. The new custom setting object contains an ID set to null and merged fields from higher in the hierarchy. You can add this new custom setting record for the user by using insert or upsert. If no custom setting data is defined in the hierarchy, the returned custom setting has empty fields, except for the SetupOwnerId field which contains the user ID.


getInstance(profileId)

Returns the custom setting data set record for the specified profile ID. The lowest level custom setting record and fields are returned. Use this when you want to explicitly retrieve data for the custom setting at the profile level.

Signature

public CustomSetting__c getInstance(ID profileId)

Parameters

profileId
Type: ID

Return Value

Type: CustomSetting__c

Usage

If no custom setting data is defined for the profile, this method returns a new custom setting record. The new custom setting object contains an ID set to null and with merged fields from your organization's default values. You can add this new custom setting for the profile by using insert or upsert. If no custom setting data is defined in the hierarchy, the returned custom setting has empty fields, except for the SetupOwnerId field which contains the profile ID.


getOrgDefaults()

Returns the custom setting data set record for the organization.

Signature

public CustomSetting__c getOrgDefaults()

Return Value

Type: CustomSetting__c

Usage

If no custom setting data is defined for the organization, this method returns an empty custom setting object.


getValues(userId)

Returns the custom setting data set record for the specified user ID.

Signature

public CustomSetting__c getValues(ID userId)

Parameters

userId
Type: ID

Return Value

Type: CustomSetting__c

Usage

Use this if you only want the subset of custom setting data that has been defined at the user level. For example, suppose you have a custom setting field that has been assigned a value of "foo" at the organizational level, but has no value assigned at the user or profile level. Using getValues(UserId) returns null for this custom setting field.

getValues(profileId)

Returns the custom setting data set for the specified profile ID.

Signature

public CustomSetting__c getValues(ID profileId)

Parameters

profileId
Type: ID

Return Value

Type: CustomSetting__c

Usage

Use this if you only want the subset of custom setting data that has been defined at the profile level. For example, suppose you have a custom setting field that has been assigned a value of "foo" at the organizational level, but has no value assigned at the user or profile level. Using getValues(ProfileId) returns null for this custom setting field.

No comments:

Post a Comment