Custom Permissions
if( System.FeatureManagement.checkPermission(
'ACustPerm' ) == true ) { ...
<apex:pageBlock rendered="{!$Permission.ACustPerm}" >
|
Custom Settings Methods
List: |
List<Games__c> gamesListCustomSetting = Games__c.getAll().values(); |
|
gamesListCustomSetting[0].GameType__c; // getAll() returns a map |
|
Games__c aSingleCustomSetting = Games__c.getValues( 'Pac Man' ); // same as getInstance() |
Hierarchy: |
Support__c supportHierarchyCustomSetting = Support__c.getInstance( profileID ); |
|
Support__c supportHierarchyCustomSetting = Support__c.getOrgDefaults(); |
|
Support__c supportHierarchyCustomSetting = Support__c.getValues( userID ); |
|
// getValues doesn't merge the non-overriden values from the hierarchy |
|
same as {!$Setup.Support__c.Config_Field__c} |
Date/DateTime Formats and Examples
myDate.format() |
format() and parse() use the current user locale |
myDate = Date.parse( '12/27/2009' ); |
myDate = Date.valueOf( '2009-12-27 23:46:00' ); |
uses standard datetime format |
myDate.toStartMonth() |
myDate.toStartWeek() |
|
dt.format() |
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.getTime() |
number of milisseconds since Jan 1, 1970 00:00 |
dt = DateTime.parse( '10/14/2011 11:46 PM' ); |
uses current user locale |
dt = Datetime.valueOf( '2011-10-14 23:46:00' ); |
uses standard datetime format |
Examples Using Named Credentials
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 Concatenation
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
HTMLENCODE() |
replaces HTML reserved characters, > becomes > |
JSENCODE() |
prepends escape on JS characters, ' becomes \' |
JSINHTMLENCODE() |
same as JSENCODE(HTMLENCODE(()) |
URLENCODE() |
replaces illegal characters in URLs, spaces becomes %20, ? becomes %21 |
myString.stripHtmlTags(); |
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>
...
|
VisualForce TabPanel (alternative 1)
<apex:tabPanel id="theTabPanel" switchType="server" value="{!varSelectedTab}" > |
<apex:tab id="tabOne" label="One" name="name1" > |
...content for tab one... |
|
// in the controller... |
public String varSelectedTab { |
get; |
set { |
// save data from tab, stop tab change if failed saving |
if( varSelectedTab == null || saveData() == true ) { |
varSelectedTab = value; |
} |
} |
} |
// Apex to change the active tab: varSelectedTab = "name1"; |
varSelectedTab = 'name1'; |
VisualForce TabPanel (alternative 2)
<apex:actionFunction name="changedTabJS" action="{!changedTab}" reRender="divContainingTabPanel,errorMsgPanel" > |
<apex:param name="tabName" assignTo="{!clickedTab}" value="" /> |
</apex:actionFunction> |
|
<apex:tabPanel id="theTabPanel" switchType="client" selectedTab="name1" value="{!varSelectedTab}" > |
<apex:tab id="tabOne" label="One" name="name1" onTabEnter="changedTabJS( 'name1' );return false;" > |
...content for tab one... |
|
// in the controller... |
public PageReference changedTab() { |
saveData(); |
if( ApexPages.getMessages().size() <= 0 ) { |
// allow tab to change if no errors |
varSelectedTab = clickedTab; |
} |
|
return null; |
} |
// Apex to change the active tab: |
varSelectedTab = "name1"; |
VisualForce apex:CommandButton with parameters
<apex:commandButton value=... action=...
reRender="someDummyDivOrPageBlock" >
<apex:param name=... value="{!...}"
assignTo="{!...}" />
|
VisualForce apex:ActionSupport with parameters
<apex:inputField value=...
<apex:actionSupport event="onchange"
action="{!...}" reRender=... >
<apex:param name=... value="{!...}"
assignTo="{!...}" />
|
VisualForce Link/Format with Param Examples
<apex:outputLink value="http://google.com/search">Search Google |
<apex:param name="q" value="{!contact.name}"/> |
<!-- this will append the q parameter to the URL --> |
|
<apex:outputText value="Formatted time now: {0, date, yyyy.MM.dd G 'at' HH:mm:ss z}"> |
<apex:param value="{! NOW() }" /> |
|
<apex:outputText value="{0, number, ###,###,##0.00}"> |
<apex:param value="{!Account.AnnualRevenue}" /> |
|
<apex:outputText value="{0, number, currency}"> |
Custom HTML Attributes in VisualForce
<apex:outputPanel layout="block" html-data-role="panel" html-data-id="menu"> |
becomes <div data-id="menu" data-role="panel"> |
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 - Miscelaneous 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
|
|
Created By
Metadata
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets