Salesforce Development Cheat Sheet
by Fernando (taurenhunter) via cheatography.com/133929/cs/27477/
Custom Permissions Date/DateTime Formats and Examples (cont)
if( System.FeatureManagement.checkPermission( dt.format( 'YYYY-‐ 2019-06-30 02:06:30.720 PM
'ACustPerm' ) == true ) { MM-dd hh:mm:‐
... ss.SSS a' )
<apex:pageBlock rendered="{!$Permission.ACustPe‐ dt.format( 'EEEEE Sunday June 30, 2019 14:06+0600
rm}" > MMMMM dd,
YYYY HH:mmZ' )
Custom Settings Methods z is timezone (CST), w is week in year, W is
List: List<Games__c> gamesListCustomSetting = Games_‐ week in month, D is day in year, u is day
_c.getAll().values(); number in week (1=Monday)
gamesListCustomSetting[0].GameType__c; // getAll() dt.getTime() number of milisseconds since Jan 1, 1970
returns a map 00:00
Games__c aSingleCustomSetting = Games__c.get‐ dt = DateTime.p‐ uses current user locale
Values( 'Pac Man' ); // same as getInstance() arse( '10/14/2011
11:46 PM' );
Hierarchy: Support__c supportHierarchyCustomSetting = Suppor‐
t__c.getInstance( profileID ); dt = Datetime.val‐ uses standard datetime format
ueOf( '2011-10-14
Support__c supportHierarchyCustomSetting = Suppor‐
23:46:00' );
t__c.getOrgDefaults();
Support__c supportHierarchyCustomSetting = Suppor‐
Examples Using Named Credentials
t__c.getValues( userID );
HttpRequest req = new HttpRequest();
// getValues doesn't merge the non-overriden values
req.setEndpoint('callout:MyNamedCredential/someP‐
from the hierarchy
ath');
same as {!$Setup.Support__c.Config_Field__c}
req.setHeader('X-Username', '{!$Credential.UserNa‐
me}');
Date/DateTime Formats and Examples
req.setHeader('X-Password', '{!$Credential.Passwo‐
myDate.format() format() and parse() use the rd}');
current user locale
req.setBody(
myDate = Date.parse( '12/27/2009' ); 'UserName:{! HTMLENCODE($Credential.User‐
myDate = Date.valueOf( '2009-‐ uses standard datetime format name)}' );
12-27 23:46:00' ); req.setHeader( 'Authorization'
myDate.toStartMonth() , 'OAuth {!$Credential.OAuthToken}' );
myDate.toStartWeek() <!-- values: Basic, Bearer or null -->
{!$Credential.AuthorizationMethod}
<!-- values: Base-64 encoded username and
dt.format()
password,
OAuth token or null -->
{!$Credential.AuthorizationHeaderValue}
{!$Credential.OAuthConsumerKey}
// usually Basic authentication goes like this
instead
By Fernando (taurenhunter) Published 10th April, 2021. Sponsored by Readable.com
Last updated 1st May, 2022. Measure your website readability!
Page 1 of 7. https://readable.com
cheatography.com/taurenhunter/
Salesforce Development Cheat Sheet
by Fernando (taurenhunter) via cheatography.com/133929/cs/27477/
Examples Using Named Credentials (cont) Test Web Service Callouts (cont)
of {!$Credential.AuthorizationHeaderValue} Test.setMock( HttpCalloutMock.class
Blob headerValue = Blob.valueOf( , new myHttpCalloutMockImpl()
username + ':' + password ); );
String authorizationHeader = 'BASIC '
+ EncodingUtil.base64Encode( header‐ Email Messaging
Value ); Messaging.SingleEmailMessage msg =
req.setHeader( 'Authorization', authorizatio‐ new Messaging.SingleEmailMessage();
nHeader ); msg.toAddresses = new String[] {
...up to 100 contact/lead/user
Test Web Service Callouts ids... };
global class myWebServiceMockImpl msg.setTargetObjectId( ...single cont/lead/user
implements WebServiceMock { id... );
global void doInvoke( Object stub msg.subject = 'Test msg';
, Object request msg.plainTextBody = 'Test body.';
, Map<String, Object> response Messaging.SingleEmailMessage[] msgList =
, String endpoint, String new List<Messaging.SingleEmailMessage> {
soapAction msg };
, String requestName Messaging.SendEmailResult[] results =
, String responseNS Messaging.sendEmail( msgList );
, String responseName // check results[ 0 ].success
, String responseType ) { // and results[ 0 ].errors[ 0 ].message)
// create/populate response element and add it Messaging.MassEmailMessage msg =
// to the response parameter new Messaging.MassEmailMessage();
// this assumes responseElement type is msg.setTargetObjectIds(
// a WSDL-generated class ...up to 250 cont/lead/user ids in List<I‐
response.put( 'response_x', responseElement ); D>... );
Test.setMock( WebServiceMock.class
, new myWebServiceMockImpl() ); String Concatenation
// in the test class List<String> soqlList = new List<String> {
global class myHttpCalloutMockImpl 'SELECT ID, ', fieldList, ' FROM ...' };
implements HttpCalloutMock { String soql = String.join( soqlList, '' );
global HTTPResponse respond( HTTPRequest req ) {
// create fake response, set HTTPResponse
// values, and return it
By Fernando (taurenhunter) Published 10th April, 2021. Sponsored by Readable.com
Last updated 1st May, 2022. Measure your website readability!
Page 2 of 7. https://readable.com
cheatography.com/taurenhunter/
Salesforce Development Cheat Sheet
by Fernando (taurenhunter) via cheatography.com/133929/cs/27477/
String Parsing with Regex Schema Functions
String template = '{0} was last updated {1}'; Record Creation with nulls or with default values
List<Object> parameters = new List<Object> { and record ids
'Universal Containers' Map<String, Schema.SObjectType> sObjTypeMap =
, DateTime.newInstance( 2018, 11, 15 ) }; Schema.getGlobalDescribe();
String formatted = String.format( template, Schema.SObjectType targetType =
paramtrs ); sObjTypeMap.get( typeName );
Pattern ptn = Pattern.compile( SObject sobj = targetType.newSObject();
'...some regex with capturing groups...' SObject sobj = targetType.newSObject(
); aRecordTypeId, loadDefaultsFlag );
Matcher mtr = ptn.matcher( '...input string...' ); Schema.SObjectType targetType = myObj__c.SObjec‐
for( Integer i = 0; i < mtr.groupCount(); i++ ) { tType;
// NOTE: group 0 is the entire expression myObj__c m = new myObj__c();
String extract = mtr.group( i ); Schema.SObjectType targetType = m.getSObject‐
} Type();
ID Prefix
SOQL Date Functions and Formats Schema.DescribeSObjectResult dscObj = descrResult[
CALENDAR_YEAR(), CALENDAR_MONTH() 0 ];
DAY_IN_YEAR() Feb 1st = 32 String objPrefix = dscObj.getKeyPrefix();
DAY_IN_MONTH()
DAY_IN_WEEK() Sunday = 1 Schema Functions - Field Details
WEEK_IN_MONTH() FieldSets
WEEK_IN_YEAR() Map<String, Schema.FieldSet> fsMap =
YESTERDAY, TODAY, TOMORROW dscObj.fieldSets.getMap();
LAST_X, THIS_X, NEXT_X Fields
where X can be (where it makes sense): Schema.DescribeFieldResult dfr =
YEAR, N_YEARS:n dscObj.fields.myField__c;
FISCAL_YEAR, N_FISCAL_YEARS:n Schema.SObjectField fieldToken =
FISCAL_QUARTER, N_FISCAL_QUARTERS:n mySObj__c.myField__c;
QUARTER, N_QUARTERS:n Schema.DescribeFieldResult dfr =
MONTH, N_MONTHS:n fieldToken.getDescribe();
90_DAYS, N_DAYS:n Map<String, Schema.SObjectField> fieldMap =
WEEK, N_WEEKS_:n Schema.SObjectType.mySObj__c.fields.get‐
Map();
Field Details
dfr.getLabel(), getName(), getDefaultValue(),
By Fernando (taurenhunter) Published 10th April, 2021. Sponsored by Readable.com
Last updated 1st May, 2022. Measure your website readability!
Page 3 of 7. https://readable.com
cheatography.com/taurenhunter/
Salesforce Development Cheat Sheet
by Fernando (taurenhunter) via cheatography.com/133929/cs/27477/
Schema Functions - Field Details (cont) FieldSet Examples
getType(), getInlineHelpText(), ... Map<String, Schema.FieldSet> fsMap =
Picklist Values Schema.SObjectType.Account.fieldSets.ge‐
List<Schema.PicklistEntry> pleList = tMap();
dfr.getPicklistValues(); Schema.DescribeSObjectResult d =
// pleList[ 0 ].getLabel(), getValue(), ... Account.sObjectType.getDescribe();
Map<String, Schema.FieldSet> fsMap =
Schema Functions - Record Types d.fieldSets.getMap();
Schema.DescribeSObjectResult[] descrResult = Schema.FieldSet fs2 = Schema.SObjectType.Account
Schema.describeSObjects( new String[] { .fieldSets.myFieldSetName;
'Account','Contact' } ); public List<Schema.FieldSetMember> fldList { get;
Schema.DescribeSObjectResult dscObj = descrResult[ set; }
0 ]; fldList = SObjectType.mySObject.FieldSets
List<Schema.RecordTypeInfo> recTypeList = .myFieldSetName.getFields();
dscObj.getRecordTypeInfos(); // fieldSet methods: getName() getLabel()
Map<Id, Schema.RecordTypeInfo> rTypeByIdMap = <apex:pageBlockTable value="{!productLineItems}"
dscObj.getRecordTypeInfosById(); var="qli" >
Map<String, Schema.RecordTypeInfo> rTypeMap = <apex:repeat value="{!$ObjectType.QuoteLineItem
dscObj.getRecordTypeInfosByDeveloper‐ .FieldSets.Sales_Forecast_Page_Detail_Fiel‐
Name(); ds}"
// ...getRecordTypeId() getName() getDeveloper‐ var="f" >
Name() <apex:column value="{!qli[ f ]}"
rendered="{! FIND( f, editableFieldList ) <= 0
Sanitizing Input }" />
<apex:column
HTMLEN‐ replaces HTML reserved characters, > becomes
rendered="{! FIND( f, editableFieldList ) > 0
CODE() >
}" >
JSENCODE() prepends escape on JS characters, ' becomes \'
<apex:facet name="header">{!f.label}
JSINHTMLE‐ same as JSENCODE(HTMLENCODE(())
</apex:facet>
NCODE()
<apex:inputField value="{!qli[ f ]}" />
URLENCODE() replaces illegal characters in URLs, spaces </apex:column>
becomes %20, ? becomes %21 </apex:repeat>
myString.stripH‐ removes tags from string ...
tmlTags();
By Fernando (taurenhunter) Published 10th April, 2021. Sponsored by Readable.com
Last updated 1st May, 2022. Measure your website readability!
Page 4 of 7. https://readable.com
cheatography.com/taurenhunter/
Salesforce Development Cheat Sheet
by Fernando (taurenhunter) via cheatography.com/133929/cs/27477/
VisualForce TabPanel (alternative 1) VisualForce apex:CommandButton with parameters
<apex:tabPanel id="theTabPanel" switchType="server" value="{!v‐ <apex:commandButton value=... action=...
arSelectedTab}" > reRender="someDummyDivOrPage‐
<apex:tab id="tabOne" label="One" name="name1" > Block" >
...content for tab one... <apex:param name=... value="{!...}"
assignTo="{!...}" />
// in the controller...
VisualForce apex:ActionSupport with parameters
public String varSelectedTab {
<apex:inputField value=...
get;
<apex:actionSupport event="onchange"
set {
action="{!...}" reRend‐
// save data from tab, stop tab change if failed saving er=... >
if( varSelectedTab == null || saveData() == true ) { <apex:param name=... value="{!...}"
varSelectedTab = value; assignTo="{!...}" />
}
VisualForce Link/Format with Param Examples
}
<apex:outputLink value="http://google.com/search">Search Google
}
<apex:param name="q" value="{!contact.name}"/>
// Apex to change the active tab: varSelectedTab = "name1";
<!-- this will append the q parameter to the URL -->
varSelectedTab = 'name1';
VisualForce TabPanel (alternative 2) <apex:outputText value="Formatted time now: {0, date, yyyy.MM.dd
G 'at' HH:mm:ss z}">
<apex:actionFunction name="changedTabJS" action="{!changedTa‐
b}" reRender="divContainingTabPanel,errorMsgPanel" > <apex:param value="{! NOW() }" />
<apex:param name="tabName" assignTo="{!clickedTab}"
value="" /> <apex:outputText value="{0, number, ###,###,##0.00}">
</apex:actionFunction> <apex:param value="{!Account.AnnualRevenue}" />
<apex:tabPanel id="theTabPanel" switchType="client" selectedT‐ <apex:outputText value="{0, number, currency}">
ab="name1" value="{!varSelectedTab}" >
Custom HTML Attributes in VisualForce
<apex:tab id="tabOne" label="One" name="name1" onTabEnte‐
r="changedTabJS( 'name1' );return false;" > <apex:outputPanel layout="block" html-data-role="panel" html-data-
id="menu">
...content for tab one...
becomes <div data-id="menu" data-role="panel">
// in the controller...
Blank Space
public PageReference changedTab() {
.
saveData();
.
if( ApexPages.getMessages().size() <= 0 ) {
.
// allow tab to change if no errors
varSelectedTab = clickedTab; Global Variables - URL Examples
}
return null;
}
// Apex to change the active tab:
varSelectedTab = "name1";
$Site.BaseUrl path prefix not ending with a /
{!$Action[ 'mySObject__c' ].New}
{!URLFOR($Action.mySObject__c.New)}
URLFOR($Action.Measurement__c.New, null
, ['CF00N3h00000HjxMj_lkid'=recordID
,'CF00N3h00000HjxMj'=theRecord.Name
,'retURL'=$CurrentPage.URL
,'saveURL'='/apex/EditMeasurements?id='+re‐
cordID
,'cancelURL'='/apex/EditMeasurements?id='+rec‐
ordID])
By Fernando (taurenhunter) Published 10th April, 2021. Sponsored by Readable.com
Last updated 1st May, 2022. Measure your website readability!
Page 5 of 7. https://readable.com
cheatography.com/taurenhunter/
Salesforce Development Cheat Sheet
by Fernando (taurenhunter) via cheatography.com/133929/cs/27477/
Global Variables - URL Examples (cont) Global Variables - Field Examples (cont)
some valid values: Clone, New, Edit, Delete {!$ObjectType.myObj__c.Fields.aField__c.Label}
, List, Merge, Tab, View, Attachment.D‐ same as Schema.DescribeFieldResult dfr =
ownload Schema.SObjectType.myObj__c.fields.aField__c;
The above corresponds to dfr.getLabel()
return new ApexPages.StandardController( other options are: inlineHelpText, length,
theRecord ).view(); picklistValues, precision, scale, type,
{!URLFOR($Asset.SLDS acessible,
, 'assets/images/profile_avatar_96.png')} calculated, ...
reference to icons from SLDS
https://lightningdesignsystem.com/icons/ Global Variables - Miscelaneous Examples
{!$Resource.TestImage} $Api.Session_ID
{!URLFOR( $Resource.TestZip, 'images/Bluehil‐ same as UserInfo.getSessionId()
ls.jpg' ) (this ID changes in VF and Lightning)
and the formula function GETSESSIONID()
Global Variables - Field Examples document.getElementById(
<apex:repeat var="f" "{!$Component.theForm.theBlock.theSection
value="{!$ObjectType.Account.FieldSets.myFi‐ .theSectionItem.theField}" )
eldSet}"> $CurrentPage.parameters.paramName
<apex:outputText value="{!f}" /> same as ApexPages.currentPage().getParameters()
same as Schema.FieldSet fs = Schema.SObje‐ .get( 'paramName' )
ctType $Setup.App_Prefs__c.Show_Help_Content__c
.Account.fieldSets.getMap().get('myFiel‐ gets value from hierarchy custom settings
dSet') {!$User.UITheme == 'Theme2'}
or Theme3 = Classic,
Schema.FieldSet fs = Schema.SObjectType.Ac‐ Theme4d = lightning,
count Theme4t = mobile app,
.fieldSets.myFieldSet; Theme4u = lightning console
{!$ObjectType.myObj__c.keyPrefix}
same as Schema.DescribeSObjectResult objDescr
=
Account.sObjectType.getDescribe();
objDescr.getKeyPrefix()
other options are: label, labelPlural, name,
accessible, createable, custom,
deletable,
mergeable, queryable, searchable,
undeletable,
updateable, ...
{!$ObjectType.myObj__c.Fields.aField__c}
{!$ObjectType[ 'myObj__c' ].fields[ 'aField__c'
].Label}
By Fernando (taurenhunter) Published 10th April, 2021. Sponsored by Readable.com
Last updated 1st May, 2022. Measure your website readability!
Page 6 of 7. https://readable.com
cheatography.com/taurenhunter/