You may need a quick reminder of a code snippet or method in apex. Here are some useful Salesforce Apex code snippets to help in daily development.
Get Session ID of the Currently Logged-In User
Salesforce doesn’t allow direct printing or logging of the session ID within transactions due to security and privacy concerns. But we can still get it through the workaround below:
System.debug(UserInfo.getOrganizationId().substring(0, 15) + ' ' + UserInfo.getSessionId().substring(15));Convert a List of SObject to Map<Id,SObject>
List<Contact> conList = [SELECT Id, Name FROM Contact LIMIT 5];
Map<Id, Contact> conMap = new Map<Id, Contact>(conList);
//Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, Name FROM Contact LIMIT 5]); Get SObject Name from a Record ID in Apex (Useful for Uncommon Metadata)
Id recordId = '0558V00002yV1XW'; // Guess what kind of object it is? I bet you can't tell from the prefix!
String sobjName = recordId.getSObjectType().getDescribe().getName(); // method 1
System.debug(sobjName);
sobjName = String.valueOf(recordId.getSObjectType()); // method 2
System.debug(sobjName);Check if the Current Org is Sandbox or Production
Boolean isSandbox = [SELECT Id, IsSandbox FROM Organization LIMIT 1].IsSandbox; // Note: Do not include it in a for-loop if this code is part of a utility method that is referenced in many places
System.debug(isSandbox);Get Today’s Date and Current Time
Date.today();
System.now();Safe Navigation Operator (?.) to avoid NullPointerException
In Apex, the Safe Navigation Operator (?.) is used to safely access properties or methods of an object that might be null, without throwing a NullPointerException. It allows you to avoid null checks before accessing properties or methods.
/* conventional way
if(accountMap.get(accId) != null) {
accountName = accountMap.get(accId).Name;
}
OR
if(accountIdAccountMap.containsKey(accId)) {
accountName = accountMap.get(accId).Name;
}
*/
accountName = accountMap.get(accId)?.Name; // simple way
// Note: It was introduced in API version 51.0, so make sure you are using API above 51.0 for thisConvert 18-Character Salesforce ID to 15-Character Case-Sensitive String
String id15 = '0018V00002Pv828';
String id18 = '0018V00002Pv828QAB';
ID id18Temp = id18;
System.assertEquals(id18Temp.to15(),id15);Get the ID of a Specific Record Type in Apex
Id recordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Business_Account').getRecordTypeId();
System.debug('Record Type ID: ' + recordTypeId);
Get the Name of the Current App the Current User Is In
UserAppInfo Stores the last Lightning app logged in to. If the user hasn’t logged into Salesforce or if the user lost access to the last accessed app, the UserAppInfo object stores a Null value.
UserAppInfo userAppInfo = [SELECT Id, AppDefinitionId FROM UserAppInfo WHERE UserId = :UserInfo.getUserId() LIMIT 1];
AppDefinition appDefinition = [SELECT DurableId, Label FROM AppDefinition Where DurableId = :userAppInfo.AppDefinitionId LIMIT 1];
system.debug(appDefinition.Label);Recalculate Formula Fields on Input SObjects in Apex
Recalculate formula fields on new or queried SObjects. If all data is present on the SObjects, SOQL limits are not affected. If the data required to evaluate a formula field is missing, that data is retrieved and limits are changed accordingly. The new formula values are stored in the SObjects themselves and overwrite previous values of formula fields.
Account a = new Account();
a.Name = 'Salesforce';
a.BillingCity = 'San Francisco';
List<Account> accounts = new List<Account>{a};
List<FormulaRecalcResult> results = Formula.recalculateFormulas(accounts);
System.assert(results[0].isSuccess());
System.debug('New value: ' + accounts[0].get('My_Formula_Field__c')); // Option 1
System.debug('New value: ' + results[0].getSObject().get(‘My_Formula_Field__c’)); // Option 2Add Thousand Separator to a Double Value and Return as a Formatted String
Double dble = Double.valueOf('3.4E+11');
String result = String.valueOf(dble.format());
System.debug(result);Get a Map of Field Names and Values from a SObject Record
In Apex, you can use the getPopulatedFieldsAsMap() method on an SObject to get a map of field names and their corresponding values for a populated record. This method returns a map where the keys are the field names (as String), and the values are the field values (which will be of type Object).
Account acc = [SELECT Id,Name FROM Account LIMIT 1];
Map<String, Object> accFieldMap = acc.getPopulatedFieldsAsMap();
// Iterate through the map and output field names and values
for (String fieldName : fieldMap.keySet()) {
System.debug('Field: ' + fieldName + ' | Value: ' + fieldMap.get(fieldName));
}Create a Default New SObject
Account obj = (Account) Account.sObjectType.newSObject(
null, // null will use the default record type for the current running user
true // load Default Values
);Get the Current Running Apex Class Name in Apex (Showing Child Class Name if Applicable)
public class ParentClass {
public ParentClass(){
String className = String.valueOf(this).substring(0,String.valueOf(this).indexOf(':')); // will get the name of ChildClass if running in ChildClass
}
}
public class ChildClass extends ParentClass {
}Hard Delete Records in Bulk
Database.emptyRecycleBin(sobjectList);
// After records are deleted from the Recycle Bin using this call, they can be queried using queryAll() for some time. Typically this time is 24 hours, but can be shorter or longer.Abbreviate a String with Ellipses (…)
Get an abbreviated version of the String, of the specified length and with ellipses appended if the current String is longer than the specified length; otherwise, returns the original String without ellipses.
String s = 'Hello Maximillian';
String s2 = s.abbreviate(8); // Hello...Get Short Form of Days of the Week (e.g., Sun, Mon)
Datetime.now().format('E'); //eg: Sun, Mon ...Join a List of Strings with a Separator (e.g., Comma)
List<String> sl = new List<String> {'a','b','c'};
system.debug(sl);
String s = String.join(sl, ',');
system.debug(s);Pad a String or Number with Leading Zeros to a Fixed Length
String s1 = '234';
String result = s1.leftPad(7,'0'); // 0000234
//If length is less than or equal to the current String size, the entire String is returned without space padding.
// this method is useful when you need to extend like a sequence number to a certain length of digits, common in APIs when you need to format data to a fixed lengthGet Community (Experience Cloud) Site URL Using ConnectApi
ConnectApi.CommunityPage cc = ConnectApi.Communities.getCommunities(); System.debug(cc.communities[0].siteUrl);Get App and Tab Describe Information Using Schema.describeTabs()
List<Schema.DescribeTabSetResult> dtsrList = Schema.describeTabs();
for(DescribeTabSetResult dtsr : dtsrList){
String appLabel = dtsr.getLabel();
System.debug('App label: ' + appLabel);
if(appLabel == 'Sales'){
List<Schema.DescribeTabResult> dtrList = dtsr.getTabs();
for(Schema.DescribeTabResult dtr : dtrList){
System.debug('Tab label: ' + dtr.getLabel());
System.debug('Tab url: ' + dtr.getUrl());
}
}Check if a String is a Valid Salesforce ID
String stringValue = '0018V00002Pv834QAB';
if(stringValue instanceOf Id) {
system.debug('It can be valid salesforce id'); // but it doesn't necessarily mean this id exists in your salesforce org
}
Id sObjectId = '0018V00002Pv834QAB';
if(Schema.Account.getSObjectType() == sObjectId.getSObjectType()) {
system.debug('This Id is an Account Id');
}Get the Number of Days in a Month for a Given Date
Date d = System.today();
Integer numberDays = date.daysInMonth(d.Year(), d.Month());
System.debug(numberDays);Dynamically Pass Child Relationship Name to Retrieve Child Records Using .getSObjects() in Apex
String query = 'SELECT Id, (SELECT Id, Name FROM Contacts) FROM Account LIMIT 10';
List<SObject> parents = Database.query(query);
for(SObject parent : parents) {
for(SObject child : parent.getSObjects('Contacts')) { // "Contacts" is the Child Relationship Name
system.debug('Child Records' + child);
}
}Using String.format() to Dynamically Populate Text Without Hardcoding in Apex
String template = '{0} was last updated {1}';
List<Object> parameters = new List<Object> {'This Account', DateTime.newInstance(2018, 11, 15) };
// for more flexibility, use custom label in apex code like: List<Object> parameters = new List<Object> {System.Label.myLabelName};
String formatted = String.format(template, parameters);
System.debug ('Formatted string is:' + formatted);Dynamically Retrieve Custom Labels in a Specific Language Using ISO Code in Apex
Common ISO codes:
Chinese (Simplified): zh_CN
Chinese (Traditional): zh_TW
Danish: da
Dutch: nl_NL
English: en_US
Finnish: fi
French: fr
German: de
Italian: it
Japanese: ja
Korean: ko
Norwegian: no
Portuguese (Brazil): pt_BR
Russian: ru
Spanish: es
Spanish (Mexico): es_MX
Swedish: sv
Thai: th
String value = System.Label.get('MyNamespace', 'MyLabel', 'fr')Extract URL Parameters in Apex Using URL.getCurrentRequestUrl()
// https://www.google.com?search=apex -> search=calendar
String queryString = URL.getCurrentRequestUrl().toExternalForm().substringAfter('?');
// OR
String queryString = URL.getCurrentRequestUrl().getQuery();Set Specific CreatedDate in Apex Test Class to Simulate Past or Future Records
Test.setCreatedDate(account.Id, Date.today().addDays(-100)); //Test.setCreatedDate(recordId, createdDatetime);
// This method let you specify a certain date and time for the CreatedDate of a record in apex tests.Set the Current PageReference for the Controller in Apex Tests
PageReference curP = Page.AccountPage;
curP.getParameters().put('acc', acc.Id);
Test.setCurrentPage(curP);
Account_Ctrl ctr = new Account_Ctrl();
ctr.someMethod(); Deliver Test Event Messages on Demand with Test.getEventBus().deliver()
Test.startTest();
// Create test events
// ...
// Publish test events with EventBus.publish()
// ...
// Deliver test events
Test.getEventBus().deliver();
// Perform validations
// ...
Test.stopTest();
/*Also, you can call Test.getEventBus().deliver() in an Apex test method outside the Test.startTest() and Test.stopTest() statement block. Doing so enables you to test event messages with asynchronous Apex.*/
Test.startTest();
// Do some tests
Test.stopTest();
// Deliver test events
Test.getEventBus().deliver();Load Test Data from Static Resources in Apex Tests
List<sObject> ls = Test.loadData(Account.sObjectType, 'testAccounts');
/*
From Setup, upload a csv file named testAccounts as Static Resource
// csv sample data
Name,Website,Phone,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry
sForceTest1,http://www.sforcetest1.com,(415) 901-7000,The Landmark @ One Market,San Francisco,CA,94105,US
sForceTest2,http://www.sforcetest2.com,(415) 901-7000,The Landmark @ One Market Suite 300,San Francisco,CA,94105,US
*/Test HTTP Callouts Using StaticResourceCalloutMock or MultiStaticResourceCalloutMock
Use StaticResourceCalloutMock built-in class to specify fake response and include response body in a static resource. Use MultiStaticResourceCalloutMock to specify multiple response bodies.
@isTest static void testCalloutWithStaticResources() {
// Use StaticResourceCalloutMock built-in class to
// specify fake response and include response body
// in a static resource.
StaticResourceCalloutMock mock = new StaticResourceCalloutMock(); //
mock.setStaticResource('mockResponse'); // mockResponse is a static resource, based on a text file with the content like {"hah":"fooled you"}
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json');
// Set the mock callout mode
Test.setMock(HttpCalloutMock.class, mock);
// Call the method that performs the callout
...
// MultiStaticResourceCalloutMock in similar use cases
MultiStaticResourceCalloutMock multimock = new MultiStaticResourceCalloutMock();
multimock.setStaticResource('https://example.com/example/test', 'mockResponse');
multimock.setStaticResource('https://example.com/example/sfdc', 'mockResponse2');
multimock.setStatusCode(200);
multimock.setHeader('Content-Type', 'application/json');
Test.setMock(HttpCalloutMock.class, multimock);
}Initialize Set/Map/List on Declaration using {}
List<String> tempList = new List<String>{'aa', 'bb', 'cc'};
Set<String> tempSet = new Set<String>{'aa', 'bb', 'cc'};
Map<String> tempMap = new Map<String,String>{
'a'=> 'Apple',
'b'=> 'banana',
'c'=> 'cat'
};
Convert Between List and Set in Apex
// List -> Set
List<String> tempList = new List<String>{'aa', 'bb', 'cc'};
Set<String> newSet = new Set<String>(tempList);
// Set -> List
Set<String> tempSet = new Set<String>{'aa', 'bb', 'cc'};
List<String> newList = new List<String>(tempSet);Get Current User’s Time Zone Offset
TimeZone tz = UserInfo.getTimeZone();
DateTime dt = Datetime.now();
system.debug('Offset ' + tz.getOffset(dt)/1000);
//like timezone in Australia/Sydney, return 10, America/New_York, return -4Get All Valid TimeZone Values in Apex
List<PicklistEntry> entries = Schema.SObjectType.User.fields.TimeZoneSidKey.picklistValues;Convert HTML Text to Plain Text in Apex
String plainText = htmlText.stripHtmlTags();Convert All Words in a Text String to Proper Case Except Those That Should Be Kept in Lower Case
public static String toProperString(String str){
if(str.trim().length() == 0) return str;
Set<String> lcaseWords = new Set<String>{
'a','an','the','and','but','or','nor','for','so','yet','at','by','in','of','off','on','out','per','to','up','via','for','from','into','like','near','over','past','than','till','upon','with'
};
String[] words = str.toLowerCase().normalizeSpace().split(' ');
String rslt = words[0].capitalize();
for(integer i=1; i<words.size()-1; i++){
if(lcaseWords.contains(words[i])) rslt += ' ' + words[i];
else rslt += ' ' + words[i].capitalize();
}
if (words.size() > 1)
rslt += ' ' + words[words.size()-1].capitalize();
return rslt;
}Get Various Salesforce Hostname URLs (e.g., mycompany.lightning.force.com.com) Accurately Using DomainCreator Class
String orgDomainHostname = DomainCreator.getOrgMyDomainHostname();
//Get the org's domain hostname url, like for REST API, you will get like: myorg.my.salesforce.com
String lightningHostname = DomainCreator.getLightningHostname();
//Get the org’s lightning hostname url, you will get like: myorg.lightning.force.com
String vfHostname = DomainCreator.getVisualforceHostname();
//Get the org’s visualforce hostname url, you will get like: myorg.vf.force.com
String setupHostname = DomainCreator.getSetupHostname();
//Get the org’s setup domain hostname url, you will get like: myorg.my.salesforce-setup.com.
String sfSiteHostname = DomainCreator.getSalesforceSitesHostname();
//Get the org’s Salesforce Sites hostname url, you will get like: myorg.my.salesforce-sites.com. If Salesforce Sites aren’t enabled, this method throws an InvalidParameterValueException.Reference: DomainCreator Class
Learn more on: Get Various Salesforce Hostname URLs Accurately and More Easily Using the DomainCreator Class in Apex