Show Menu
Cheatography

Salesforce Development Cheat Sheet by

Salesforce Development

Custom Permis­sions

if( System.Fe­atu­reM­ana­gem­ent.ch­eck­Per­mis­sion( 
                        'ACust­P­erm­' ) == true ) { ...


<ap­ex:­pag­eBlock render­ed=­"­{!$­Per­mis­sio­n.ACust­P­erm­}" >

Custom Settings Methods

List:
List<G­ame­s__­c> gamesL­ist­Cus­tom­Setting = Games_­_c.g­et­All­().v­al­ues();
 
gamesL­ist­Cus­tom­Set­tin­g[0­].G­ame­Typ­e__c; // getAll() returns a map
 
Games__c aSingl­eCu­sto­mSe­tting = Games_­_c.g­et­Values( 'Pac Man' ); // same as getIns­tance()
Hierarchy:
Support__c suppor­tHi­era­rch­yCu­sto­mSe­tting = Suppor­t__­c.g­etI­nst­ance( profileID );
 
Support__c suppor­tHi­era­rch­yCu­sto­mSe­tting = Suppor­t__­c.g­etO­rgD­efa­ults();
 
Support__c suppor­tHi­era­rch­yCu­sto­mSe­tting = Suppor­t__­c.g­etV­alues( userID );
 
// getValues doesn't merge the non-ov­erriden values from the hierarchy
 
same as {!$Set­up.S­up­por­t__­c.C­onf­ig_­Fie­ld__c}

Date/D­ateTime Formats and Examples

myDate.fo­rmat()
format() and parse() use the current user locale
myDate = Date.p­arse( '12/27­/2009' );
myDate = Date.v­alueOf( '2009-­12-27 23:46:00' );
uses standard datetime format
myDate.to­Sta­rtM­onth()
myDate.to­Sta­rtW­eek()
 
dt.for­mat()
dt.format( 'YYYY-­MM-dd hh:mm:­ss.SSS a' )
2019-06-30 02:06:­30.720 PM
dt.format( 'EEEEE MMMMM dd, YYYY HH:mmZ' )
Sunday June 30, 2019 14:06+0600
 
z is timezone (CST), w is week in year, W is week in month, D is day in year, u is day number in week (1=Monday)
dt.get­Time()
number of miliss­econds since Jan 1, 1970 00:00
dt = DateTi­me.p­arse( '10/14­/2011 11:46 PM' );
uses current user locale
dt = Dateti­me.v­al­ueOf( '2011-­10-14 23:46:00' );
uses standard datetime format

Examples Using Named Creden­tials

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:MyNamedCredential/somePath');

req.setHeader('X-Username', '{!$Credential.UserName}');
req.setHeader('X-Password', '{!$Credential.Password}');
req.setBody( 
     'UserName:{! HTMLENCODE($Credential.Username)}' );
req.setHeader( 'Authorization'
      , 'OAuth {!$Credential.OAuthToken}' );

<!-- values:  Basic, Bearer or null -->
{!$Credential.AuthorizationMethod}

<!-- values:  Base-64 encoded username and password, 
OAuth token or null -->
{!$Credential.AuthorizationHeaderValue}

{!$Credential.OAuthConsumerKey}

// usually Basic authentication goes like this instead 
of {!$Credential.AuthorizationHeaderValue}
Blob headerValue = Blob.valueOf( 
                      username + ':' + password );
String authorizationHeader = 'BASIC ' 
            + EncodingUtil.base64Encode( headerValue );
req.setHeader( 'Authorization', authorizationHeader );

Test Web Service Callouts

global class myWebServiceMockImpl 
                   implements WebServiceMock {
	global void doInvoke( Object stub
                   , Object request
                   , Map<String, Object> response
                   , String endpoint, String soapAction
                   , String requestName
                   , String responseNS
                   , String responseName
                   , String responseType ) {
	// create/populate response element and add it 
        // to the response parameter
	// this assumes responseElement type is 
        // a WSDL-generated class 
	response.put( 'response_x', responseElement );

Test.setMock( WebServiceMock.class
                   , new myWebServiceMockImpl() ); 
        // in the test class

global class myHttpCalloutMockImpl 
                   implements HttpCalloutMock {
	global HTTPResponse respond( HTTPRequest req ) {
	// create fake response, set HTTPResponse 
        // values, and return it

Test.setMock( HttpCalloutMock.class
                   , new myHttpCalloutMockImpl() );

Email Messaging

Messaging.SingleEmailMessage msg = 
               new Messaging.SingleEmailMessage();
msg.toAddresses = new String[] { 
               ...up to 100 contact/lead/user ids... };
msg.setTargetObjectId( ...single cont/lead/user id... );
msg.subject = 'Test msg';
msg.plainTextBody = 'Test body.';
Messaging.SingleEmailMessage[] msgList = 
         new List<Messaging.SingleEmailMessage> { msg };
Messaging.SendEmailResult[] results = 
         Messaging.sendEmail( msgList );

// check results[ 0 ].success 
// and results[ 0 ].errors[ 0 ].message)

Messaging.MassEmailMessage msg = 
         new Messaging.MassEmailMessage();
msg.setTargetObjectIds( 
       ...up to 250 cont/lead/user ids in List<ID>... );

String Concat­enation

List<String> soqlList = new List<String> { 
        'SELECT ID, ', fieldList, ' FROM ...' };

String soql = String.join( soqlList, '' );

String Parsing with Regex

String template = '{0} was last updated {1}';
List<Object> parameters = new List<Object> {
	'Universal Containers'
        , DateTime.newInstance( 2018, 11, 15 ) };
String formatted = String.format( template, paramtrs );

Pattern ptn = Pattern.compile( 
          '...some regex with capturing groups...' );
Matcher mtr = ptn.matcher( '...input string...' );
for( Integer i = 0; i < mtr.groupCount(); i++ ) {
	// NOTE:  group 0 is the entire expression
	String extract = mtr.group( i );
}

SOQL Date Functions and Formats

CALENDAR_YEAR(), CALENDAR_MONTH()
DAY_IN_YEAR()	                    Feb 1st = 32
DAY_IN_MONTH()
DAY_IN_WEEK()	                    Sunday = 1
WEEK_IN_MONTH()
WEEK_IN_YEAR()
YESTERDAY, TODAY, TOMORROW
LAST_X, THIS_X, NEXT_X
    where X can be (where it makes sense): 
        YEAR, N_YEARS:n
        FISCAL_YEAR, N_FISCAL_​YEARS:n
        FISCAL_QUARTER, N_FISCAL_​QUARTERS:n
        QUARTER, N_QUARTERS:n
        MONTH, N_MONTHS:n
        90_DAYS, N_DAYS:n
        WEEK, N_WEEKS_:n

Schema Functions

Record Creation with nulls or with default values 
    and record ids

Map<String, Schema.SObjectType> sObjTypeMap = 
    Schema.getGlobalDescribe();
Schema.SObjectType targetType = 
    sObjTypeMap.get( typeName );
SObject sobj = targetType.newSObject();
SObject sobj = targetType.newSObject( 
    aRecordTypeId, loadDefaultsFlag );

Schema.SObjectType targetType = myObj__c.SObjectType;

myObj__c m = new myObj__c();
Schema.SObjectType targetType = m.getSObjectType();

ID Prefix
Schema.DescribeSObjectResult dscObj = descrResult[ 0 ];	
String objPrefix = dscObj.getKeyPrefix();

Schema Functions - Field Details

FieldSets
Map<String, Schema.FieldSet> fsMap = 
        dscObj.fieldSets.getMap();

Fields
Schema.DescribeFieldResult dfr = 
        dscObj.fields.myField__c;

Schema.SObjectField fieldToken = 
        mySObj__c.myField__c;
Schema.DescribeFieldResult dfr = 
        fieldToken.getDescribe();

Map<String, Schema.SObjectField> fieldMap = 
        Schema.SObjectType.mySObj__c.fields.getMap();

Field Details
dfr.getLabel(), getName(), getDefaultValue(), 
    getType(), getInlineHelpText(), ...

Picklist Values
List<Schema.PicklistEntry> pleList = 
    dfr.getPicklistValues();
// pleList[ 0 ].getLabel(), getValue(), ...

Schema Functions - Record Types

Schema.DescribeSObjectResult[] descrResult = 
	Schema.describeSObjects( new String[] { 
            'Account','Contact' } );
Schema.DescribeSObjectResult dscObj = descrResult[ 0 ];	
List<Schema.RecordTypeInfo> recTypeList = 
        dscObj.getRecordTypeInfos();
Map<Id, Schema.RecordTypeInfo> rTypeByIdMap = 
        dscObj.getRecordTypeInfosById();
Map<String, Schema.RecordTypeInfo> rTypeMap = 
        dscObj.getRecordTypeInfosByDeveloperName();
// ...getRecordTypeId() getName() getDeveloperName()
 

Sanitizing Input

HTMLEN­CODE()
replaces HTML reserved charac­ters, > becomes &gt;
JSENCODE()
prepends escape on JS charac­ters, ' becomes \'
JSINHT­MLE­NCODE()
same as JSENCO­DE(­HTM­LEN­COD­E(())
URLENC­ODE()
replaces illegal characters in URLs, spaces becomes %20, ? becomes %21
myStri­ng.s­tr­ipH­tml­Tags();
removes tags from string

FieldSet Examples

Map<String, Schema.FieldSet> fsMap = 
      Schema.SObjectType.Account.fieldSets.getMap();
Schema.DescribeSObjectResult d = 
      Account.sObjectType.getDescribe();
Map<String, Schema.FieldSet> fsMap = 
      d.fieldSets.getMap();

Schema.FieldSet fs2 = Schema.SObjectType.Account
      .fieldSets.myFieldSetName;

public List<Schema.FieldSetMember> fldList { get; set; }
fldList = SObjectType.mySObject.FieldSets
      .myFieldSetName.getFields();

// fieldSet methods:  getName() getLabel()

<apex:pageBlockTable value="{!productLineItems}" 
      var="qli" >

<apex:repeat value="{!$ObjectType.QuoteLineItem
      .FieldSets.Sales_Forecast_Page_Detail_Fields}" 
      var="f" >
   <apex:column value="{!qli[ f ]}"
    rendered="{! FIND( f, editableFieldList ) <= 0 }" />

   <apex:column 
    rendered="{! FIND( f, editableFieldList ) > 0 }" >
       <apex:facet name="header">{!f.label}
       </apex:facet>
       <apex:inputField value="{!qli[ f ]}" />
   </apex:column>
</apex:repeat>
...

Visual­Force TabPanel (alter­native 1)

<ap­ex:­tab­Panel id="­the­Tab­Pan­el" switch­Typ­e="s­erv­er" value=­"­{!v­arS­ele­cte­dTa­b}" >
 ­ ­ ­ ­<ap­ex:tab id="­tab­One­" label=­"­One­" name="n­ame­1" >
 ­ ­ ­ ­ ­ ­ ­ ...c­ontent for tab one...
 
// in the contro­ller...
public String varSel­ect­edTab {
 ­ ­ ­ get;
 ­ ­ ­ set {
 ­ ­ ­ ­ ­ ­ ­ // save data from tab, stop tab change if failed saving
 ­ ­ ­ ­ ­ ­ ­ if( varSel­ect­edTab == null || saveData() == true ) {
 ­ ­ ­ ­ ­ ­ ­ ­ ­ ­ ­ ­var­Sel­ect­edTab = value;
 ­ ­ ­ ­ ­ ­ ­ }
 ­ ­ ­ }
}
// Apex to change the active tab: varSel­ect­edTab = "­nam­e1";
varSel­ect­edTab = 'name1';

Visual­Force TabPanel (alter­native 2)

<ap­ex:­act­ion­Fun­ction name="c­han­ged­Tab­JS" action­="{!­cha­nge­dTa­b}" reRend­er=­"­div­Con­tai­nin­gTa­bPa­nel­,er­ror­Msg­Pan­el" >
 ­ ­ ­ ­<ap­ex:­param name="t­abN­ame­" assign­To=­"­{!c­lic­ked­Tab­}" value=­"­" />
</a­pex­:ac­tio­nFu­nct­ion>
 
<ap­ex:­tab­Panel id="­the­Tab­Pan­el" switch­Typ­e="c­lie­nt" select­edT­ab=­"­nam­e1" value=­"­{!v­arS­ele­cte­dTa­b}" >
 ­ ­ ­ ­<ap­ex:tab id="­tab­One­" label=­"­One­" name="n­ame­1" onTabE­nte­r="c­han­ged­TabJS( 'name1' );return false;­" >
 ­ ­ ­ ­ ­ ­ ­ ...c­ontent for tab one...
 
// in the contro­ller...
public PageRe­ference change­dTab() {
 ­ ­ ­ ­sav­eDa­ta();
 ­ ­ ­ if( ApexPa­ges.ge­tMe­ssa­ges­().s­ize() <= 0 ) {
 ­ ­ ­ ­ ­ ­ ­ // allow tab to change if no errors
 ­ ­ ­ ­ ­ ­ ­ ­var­Sel­ect­edTab = clicke­dTab;
 ­ ­ ­ }
 ­ ­ ­ 
 ­ ­ ­ ­return null;
}
// Apex to change the active tab:
varSel­ect­edTab = "­nam­e1";

Visual­Force apex:C­omm­and­Button with parameters

<apex:commandButton value=... action=... 
                    reRender="someDummyDivOrPageBlock" >
	<apex:param name=... value="{!...}" 
                    assignTo="{!...}" />

Visual­Force apex:A­cti­onS­upport with parameters

<apex:inputField value=...
	<apex:actionSupport event="onchange" 
                       action="{!...}" reRender=... >
		<apex:param name=... value="{!...}" 
                       assignTo="{!...}" />

Visual­Force Link/F­ormat with Param Examples

<ap­ex:­out­putLink value=­"­htt­p:/­/go­ogl­e.c­om/­sea­rch­"­>Search Google
 ­ ­ ­ ­<ap­ex:­param name="q­" value=­"­{!c­ont­act.na­me}­"­/>
 ­ ­ ­ ­<!-- this will append the q parameter to the URL -->
 
<ap­ex:­out­putText value=­"­For­matted time now: {0, date, yyyy.MM.dd G 'at' HH:mm:ss z}">
 ­ ­ ­ ­<ap­ex:­param value=­"{! NOW() }" />
 
<ap­ex:­out­putText value=­"{0, number, ###,##­#,#­#0.0­0}­">
 ­ ­ ­ ­<ap­ex:­param value=­"­{!A­cco­unt.An­nua­lRe­ven­ue}­" />
 
<ap­ex:­out­putText value=­"{0, number, curren­cy}­">

Custom HTML Attributes in Visual­Force

<ap­ex:­out­put­Panel layout­="bl­ock­" html-d­ata­-ro­le=­"­pan­el" html-d­ata­-id­="me­nu">
becomes <div data-i­d="m­enu­" data-r­ole­="pa­nel­">

Blank Space

.
.
.

Global Variables - URL Examples

$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='+recordID
   ,'cancelURL'='/apex/EditMeasurements?id='+recordID])
	some valid values:  Clone, New, Edit, Delete
         , List, Merge, Tab, View, Attachment.Download

The above corresponds to 
   return new ApexPages.StandardController( 
               theRecord ).view();

{!URLFOR($Asset.SLDS
      , 'assets/images/profile_avatar_96.png')}
	reference to icons from SLDS 
        https://lightningdesignsystem.com/icons/


{!$Resource.TestImage}
{!URLFOR( $Resource.TestZip, 'images/Bluehills.jpg' )

Global Variables - Field Examples

<apex:repeat var="f"
    value="{!$ObjectType.Account.FieldSets.myFieldSet}">
	<apex:outputText value="{!f}" />

    same as Schema.FieldSet fs = Schema.SObjectType
        .Account.fieldSets.getMap().get('myFieldSet')
    or 
    Schema.FieldSet fs = Schema.SObjectType.Account
       .fieldSets.myFieldSet;

{!$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}
{!$ObjectType.myObj__c.Fields.aField__c.Label}

same as Schema.DescribeFieldResult dfr = 
     Schema.SObjectType.myObj__c.fields.aField__c;
     dfr.getLabel()

other options are:  inlineHelpText, length, 
     picklistValues, precision, scale, type, acessible, 
     calculated, ...

Global Variables - Miscel­aneous Examples

$Api.Session_ID
      same as UserInfo.getSessionId()
      (this ID changes in VF and Lightning) 
      and the formula function GETSESSIONID()

document.getElementById( 
        "{!$Component.theForm.theBlock.theSection
           .theSectionItem.theField}" )

$CurrentPage.parameters.paramName
	same as ApexPages.currentPage().getParameters()
              .get( 'paramName' )

$Setup.App_Prefs__c.Show_Help_Content__c
     gets value from hierarchy custom settings

{!$User.UITheme == 'Theme2'}
     Theme3 = Classic,
     Theme4d = lightning,
     Theme4t = mobile app, 
     Theme4u = lightning console
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Oracle APEX 5 Keyboard Shortcuts Keyboard Shortcuts
          Salesforce Javascript Functional Cheat Sheet