Professional Documents
Culture Documents
SF Apex Code Cheatsheet FINAL
SF Apex Code Cheatsheet FINAL
APP LOGIC
Overview
Description
Example
abstract
Declares a class
that contains abstract
methods that only have
their signature and no
body defined. Can also
define methods.
while(reader.hasNext()) {
if (reader.getEventType() == END) {
break;
};
// process
reader.next();
}
break
Identifies a block of
code that can handle
a particular type of
exception
try {
// Your code here
class
Defines a class
continue
while (checkBoolean) {
if (condition)
{continue; }
// do some work
}
do
Defines a do-while
loop that executes
repeatedly while a
Boolean condition
remains true
Integer count = 1;
do {
System.debug(count);
count++;
} while (count < 11);
else
Integer x, sign;
if (x==0) {
sign = 0;
} else {
sign = 1;
}
enum
Defines an
enumeration type on
a finite set of values
extends
Defines a class or
interface that extends
another class or
interface
catch
false
Identifies an untrue
value assigned to a
Boolean
} catch (ListException e) {
// List Exception handling code here
}
try {
Integer i;
if (i < 5) throw new MyException();
} catch (MyException e) {
// Your MyException handling code
}
Boolean isNotTrue = false;
Keyword
Description
Example
final
finally
Identifies a block of
code that is guaranteed
to execute
try {
// Your code here
} catch (ListException e) {
// List Exception handling code
} finally {
// will execute with or without
// exception
}
for
global
Defines a class,
method, or variable
that can be used by any
Apex that has access
to the class, not just
the Apex in the same
application.
if
Defines a condition,
used to determine
whether a code block
should be executed
Integer i = 1;
if (i > 0) {
// do something;
}
implements
Declares a class
or interface that
implements an
interface
instanceOf
Verifies at runtime
whether an object is
actually an instance of
a particular class
if (reports.get(0) instanceof
CustomReport) {
// Can safely cast CustomReport
c = (CustomReport)
reports.get(0);
} else {
// Do something with the noncustom-report.
}
interface
Defines a data
type with
method signatures.
Classes implement
interfaces. An interface
can extend another
interface.
public interface PO {
public void doWork();
}
public class MyPO implements PO {
public override doWork() {
// actual implementation
}
}
http://developer.salesforce.com
Keyword
Description
Example
Keyword
Description
Example
new
trigger
Defines a trigger on an
sObject
null
Boolean b = null;
override
Defines a method or
property as overriding
another defined as virtual
in a class being extended
or implemented
protected
Defines a method or
variable that is visible to
any inner classes in the
defining Apex class
public
Defines a method or
variable that can be
used by any Apex in this
application or namespace
return
static
Defines a method or
variable that is only
initialized once, and is
associated with an (outer)
class, and initialization
code
Invokes a constructor on a
superclass
private
super
try
try {
// Your code here
webService
} catch (ListException e) {
// List Exception handling code
// here
}
Integer count=1;
while (count < 11) {
System.debug(count);
count++;
}
with
sharing
// Initialization code
static {
MY_INT = 10;
}
}
without
sharing
virtual
this
Throws an exception,
signaling that an error
has occurred
Executes a block of
code repeatedly as long
as a particular Boolean
condition remains true
Defines a method as a
unit test
transient
true
while
testmethod
throw
if (a.Name != 'okToDelete') {
a.addError(
'You can\'t delete this record!');
}
}
}
Annotations
Annotation Description
@future
Example
global class MyFutureClass {
@future
static void myMethod(
String a, Integer i) {
System.debug(
'Method called with: ' + a +
' and ' + i);
// do callout, other long
// running code
}
}
Annotations
Annotation
Description
Primitive Types
Example
@isTest(
OnInstall=true)
@isTest(OnInstall=true)
private class TestClass {
}
@isTest(
SeeAllData=true)
@isTest(SeeAllData=true)
private class TestClass {
}
@isTest
@deprecated
@readOnly
Denotes methods that
private void doQuery() {
can perform queries
unrestricted by the number }
of returned rows limit for
a request
@readOnly
@remoteAction
@restResource
@httpGet,
@httpPost,
@httpPatch,
@httpPut,
@httpDelete
@remoteAction
global static String getId(
String s) {
}
@restResource(urlMapping=
'/Widget/*')
global with sharing class
MyResource() {
}
@httpGet
global static MyWidget__c
doGet() {
}
@httpDelete
global static void doDelete() {
}
Type
Description
Example
Decimal
Double
Double d=3.14159;
ID
ID id='00300000003T2PGAA0';
Integer
Integer i = 1;
Long
Long l = 2147483648L;
String
Time
Particular time
Time myTime =
Time.newInstance(18, 30, 2, 20);
Integer myMinutes = myTime.
minute();
Collection Types
List
Map
Set
@httpPost
global static void doPost() {
}
Primitive Types
Type
Description
Example
Blob
Blob myBlob =
Blob.valueof('idea');
Boolean
Date
Particular day
Datetime
Datetime myDateTime =
Datetime.now();
Datetime newd =
myDateTime. addMonths(2);
Ordered collection
of typed primitives,
sObjects, objects, or
collections that are
distinguished by
their indices
Collection of key-value
pairs where each
unique key maps to a
single value. Keys can
be any primitive data
type, while values can
be a primitive, sObject,
collection type, or an
object.
Operators
isExecuting
Returns true if the current context for the Apex code is a trigger only
isInsert
isUpdate
isDelete
isBefore
Returns true if this trigger was fired before any record was saved
isAfter
Returns true if this trigger was fired after all records were saved
isUndelete
Returns true if this trigger was fired after a record is recovered from
the Recycle Bin
new
newMap
A map of IDs to the new versions of the sObject records. (Only available in
before update, after insert, and after update triggers.)
old
Variable
Operators
oldMap
size
The total number of records in a trigger invocation, both old and new.
Description
Example
insert
Adds one or
more records
delete
Deletes one or
more records
merge
Merges up to
three records of
the same type
into one of the
records, deleting
the others, and
re-parenting any
related records
undelete
Restores one or
more records from
the Recycle Bin
update
Modifies one or
more existing
records
upsert
Creates new
records and
updates existing
records
abortJob
assert
assertEquals
assertNotEquals currentPageReference currentTimeMillis
debug
isRunningTest
now
process resetPassword runAs
schedule setPassword submit
today
Math
Describe
DescribeFieldResult
getByteLength
getCalculatedFormula getController
getDefaultValue
getDefaultValueFormula getDigits
getInlineHelpText getLabel
getLength
getLocalName getName
getPicklistValues
getPrecision getReferenceTo getRelationshipName
getRelationshipOrder
getScale
getSOAPType
getSObjectField getType
isAccessible
isAutoNumber isCalculated isCaseSensitive
isCreateable isCustom
isDefaultedOnCreate
isDependantPicklist isDeprecatedAndHidden isExternalID
isFilterable isGroupable isHtmlFormatted
isIdLookup isNameField isNamePointing
isNillable
isPermissionable isRestrictedDelete
isRestrictedPicklist isSortable
isUnique
isUpdateable
isWriteRequiresMasterRead
Schema.DescribeFieldResult f = Schema.SObjectType.Account.fields.Name;
LoggingLevel
ERROR
WARN
INFO
DEBUG
FINE
FINER
FINEST
getAggregateQueries getLimitAggregateQueries
getCallouts
getLimitCallouts
getChildRelationshipsDescribes getDMLRows
getLimitChildRelationshipsDescribes getLimitDMLRows
getCPUTime
getLimitCPUTime
getDMLRows
getLimitDMLRows
getDMLStatements
getLimitDMLStatements
getEmailInvocations getLimitEmailInvocations
getFieldsDescribes getLimitFieldsDescribes
getFindSimilarCalls getLimitFindSimilarCalls
getFutureCalls
getLimitFutureCalls
getHeapSize
getLimitHeapSize
getPicklistDescribes getLimitPicklistDescribes
getQueries
getLimitQueries
getQueryLocatorRows getLimitQueryLocatorRows
getQueryRows
getLimitQueryRows
getRecordTypesDescribes getLimitRecordTypesDescribes
getRunAs
getLimitRunAs
getSavepointRollbacks
getLimitSavepointRollbacks
getSavepoints
getLimitSavepoints
getScriptStatements getLimitScriptStatements
getSoslQueries
getLimitSoslQueries
UserInfo
getDefaultCurrency getFirstName
getLanguage
getLastName getLocale getName
getOrganizationId getOrganizationName getProfileId
getSessionId getUITheme getUIThemeDisplayed
IsMultiCurrencyOrganization
String result = UserInfo.getLocale();
System.assertEquals('en_US', result);
10132014