Saturday, March 21, 2015

Use Custom Setting Efficiently in Apex

Use Custom Setting Efficiently in Apex

What is Custom Setting?

Custom Settings are similar to custom objects and gives ability to create custom sets of data. The data can be associate to an organisation, profile, or specific user. 

Data Types for Custom Setting fields:


  • Checkbox
  • Currency
  • Date
  • DateTime
  • Email
  • Number
  • Percent
  • Phone
  • Text
  • Text Area
  • URL

Note: The data in these fields are cached with the application.

Types of Custom Settings

There are two types of custom settings:

  • List
  • Hierarchy


List

A type of custom setting that provides a reusable set of static data that can be accessed across your organisation.

For example you have a custom setting for Status Code. It has 2 fields:
Name (object Name field same as when you create a custom object)
Code (Text field)

How to access this List type custom setting in Apex:

// Method 1
// Returns a map of the data sets defined for the custom setting.
Map<String, Status_Code__c> mapStatusCodeCustomSetting = Status_Code__c.getAll();
for(Status_Code__c mandatoryRoles : mapStatusCodeCustomSetting.values()){
}

// Method 2
for(Status_Code__c mandatoryRoles : Status_Code__c.getAll().values()){
}

// Method 3    
Status_Code__c statusCodeCS = Status_Code__c.getValues('400');
String statusCode = statusCodeCS.Code__c;

// Method 4
String statusCode = Status_Code__c.getValues('400').Code__c;


Hierarchy

A type of custom setting that uses a built-in hierarchical logic that checks the organisation, profile, and user settings for the current user and returns the most specific, or “lowest,” value. 

How to access this Hierarchy type custom setting in Apex:

// Method 1
// Returns a custom setting data set record for the current user.
Authentication_Token_Setting__c authTokenSetting = Authentication_Token_Setting__c.getInstance();

// Method 2
// Returns the custom setting data set record for the specified User ID or Profile ID. 
Authentication_Token_Setting__c authTokenSetting = Authentication_Token_Setting__c.getInstance(Userinfo.getUserId());

// Method 3
// Returns the custom setting data set record for the organization.
Authentication_Token_Setting__c authTokenSetting = Authentication_Token_Setting__c.getOrgDefaults();

// Method 4
// Returns the custom setting data set record for the specified User ID or Profile ID.
Authentication_Token_Setting__c authTokenSetting = Authentication_Token_Setting__c.getValues(Userinfo.getUserId());

Note:

  • For Apex saved using Salesforce API version 21.0 or earlier, this method returns the custom setting data set  record with fields merged from field values defined at the lowest hierarchy level, starting with the user.  Also, if no custom setting data is defined in the hierarchy, this method returns null.
  • For Apex saved using Salesforce API version 22.0 or later, 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.


Benefits of Using Custom Setting:


  • Custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database.
  • Custom settings data can be used by formula fields, Visualforce, Apex, and the Force.com Web Services API.
  • You can make visibility of custom setting public or protected.


DON'T:

Don't query custom settings data using Standard Object Query Language (SOQL). It doesn't make use of the application cache and is similar to querying a custom object. 

Note: You can create up to 2 MB data in custom settings.



Use Static Resources to Create Custom Settings Data

// Publicly exposed Data Factory Class for Test class
@isTest
public class TestDataFactory{
    public static List<Status_Code__c> createStatusCodeCustomSettingByStaticResource(){
        // Create records for a custom setting Status_Code__c
        // using a sample .CSV file "StatusCodes" stored in Static Resource
        List<Status_Code__c> lstStatusCodeSetting = Test.loadData(Status_Code__c.sObjectType, 'StatusCodes');
        return lstStatusCodeSetting;
    }    
}

// Main Test Class to Test the functionality
@isTest
private class StatusCodeTest{
    @isTest
    static void testStatusCode(){
        // Call publicly exposed method of Test class to create data in a custom setting "Status_Code__c"
        // via CSV file stored in a Static Resource 
        List<Status_Code__c> lstStatusCodeSetting = TestDataFactory.createStatusCodeCustomSettingByStaticResource(); 
    }
}

Useful Resources: