Sunteți pe pagina 1din 8

Apex Code

Cheatsheet

Overview
Apex code is a strongly-typed programming language that executes on the Force.com platform. Using Apex code, you can add business logic to
applications, write database triggers, and create Visualforce controllers. Apex code has a tight integration with the database and query language, web
services, and email handling support. It also includes features such as asynchronous execution and support for testing.

Important Reserved Words Important Reserved Words continued


Keyword Description Example Keyword Description Example

abstract Declares a class enum Defines an public enum Season {WINTER,


that contains public abstract class Foo { SPRING, SUMMER, FALL};
protected void method1() { /* */ } enumeration
Season e = Season.WINTER;
abstract abstract Integer abstractMethod(); type on a
methods that } finite set
only have of values
their signature
and no body extends Defines public class MyException extends
defined. Can Exception {}
a class or
also define interface try {
methods. that extends Integer i;
another class if (i < 5) throw new MyException();
break Exits the entire } catch (MyException e) {
while(reader.hasNext()) { or interface
loop // Your MyException handling code
if (reader.getEventType() == END) {
}
break;
};
// process false Identifies an Boolean isNotTrue = false;
reader.next(); untrue value
}
assigned to
a Boolean
catch Identifies
try { final Defines public class myCls {
a block of
// Your code here static final Integer intConstant;
code that constants }
can handle a } catch (ListException e) {
particular type // List Exception handling code here finally Identifies a try {
}
of exception block of // Your code here
} catch (ListException e) {
code that is // List Exception handling code
class Defines a class guaranteed } finally {
private class Foo {
to execute // will execute with or without
private Integer x;
// exception
public Integer getX() { return x; }
}
}

for Defines a for (Integer i = 0, j = 0; i < 10;


continue Skips to the i++) { System.debug(i+1);
loop. The
while (checkBoolean) { }
next iteration three types of
if (condition)
of the loop {continue; } for loops are: Integer[] myInts = new Integer[]
// do some work iteration using {1, 8, 9};
} for (Integer i : myInts) {
a variable,
System.debug(i);
iteration over }
do Defines a a list, and
Integer count = 1; iteration over String s = 'Acme';
do-while loop for (Account a : [SELECT Id, Name,
do { a query
that executes System.debug(count); FROM account
repeatedly count++; WHERE Name LIKE :(s+'%')]) {
(at least } while (count < 11); // Your code
}
once) while
a Boolean
global Defines a global class myClass {
condition
remains true class, method, webService static void
makeContact(String lastName) {
or variable // do some work
else Defines the that can be }
Integer x, sign; used by any
else portion
if (x==0) {
of an if-else sign = 0; Apex that
statement, } else { has access to
that executes sign = 1; the class, not
} just the Apex
if the initial
evaluation is in the same
untrue application.
Apex Code Cheatsheet

Important Reserved Words continued Important Reserved Words continued


Keyword Description Example Keyword Description Example

if Defines a Integer i = 1; private Defines a public class OuterClass {


if (i > 0) { class, method, // Only visible to methods and
condition, // do something; // statements within OuterClass
used to } or variable private static final Integer
determine that is only myInt;
whether a known locally, }
code block within the
should be section of
executed code in which
it is defined
implements Declares global class CreateTaskEmailExample
implements Messaging. protected Defines a public class Foo {
a class or InboundEmailHandler { method or public void quiteVisible();
interface that global Messaging.InboundEmailResult protected void
implements handleInboundEmail(Messaging. variable that is
lessVisible();
an interface inboundEmail email, visible to any
}
Messaging.InboundEnvelope env){ inner classes
// do some work, return value; in the defining
}
} Apex class,
and to classes
that extend
instanceOf Verifies at if (reports.get(0) instanceof the defining
CustomReport) {
runtime class
// Can safely cast
whether an CustomReport c = (CustomReport)
object is reports.get(0); public class Foo {
} else {
public Defines a
actually an public void quiteVisible();
// Do something with the method
instance of a private void
non-custom-report. or variable
particular class } almostInvisible();
that can be
}
used by any
interface Defines a data public interface PO { Apex in this
type with public void doWork(); application or
} namespace
method public class MyPO implements PO {
signatures. public override doWork() {
Classes // actual implementation
}
implement
}
interfaces. return Returns a public Integer
An interface value from meaningOfLife() {
can extend a method return 42;
another }
interface.
static Defines public class OuterClass {
initialization // Associated with instance
new Creates a Foo f = new Foo(); public static final Integer
new object, MyObject__c mo = code, or a myInt;
new MyObject__c(Name= 'hello'); method or
sObject, or List<Account> la = new // Initialization code
collection List<Account>(); variable that static {
is initialized myInt = 10;
instance }
only once and }
is associated
null Identifies a Boolean b = null; with a class
null constant
that can be public class
super Invokes a
assigned to AnotherChildClass extends
constructor
any variable InnerClass {
or method
AnotherChildClass(String
on a parent
s) {
override Defines a public virtual class V { class that's
public virtual void foo() super();
method as designated // different constructor,
{/*Does nothing*/}
overriding } as virtual }
another or abstract. }
method public class RealV implements V { Can be used
public override void foo() { in methods
on a class // Do something real
thats being } only if they're
extended or } designated
implemented. with the
override
keyword.
Important Reserved Words continued Important Reserved Words continued
Keyword Description Example Keyword Description Example

webservice Defines a global class MyWebService {


this Represents public class Foo {
webService static Id
the current public Foo(String s) { /* */} static method makeContact(
public Foo() { that is
instance of a String lastName, Account a) {
this('memes repeat'); }
class, or calls }
exposed as a
Web service Contact c = new Contact(
the previous LastName = 'Weissman',
constructor in method AccountId = a.Id);
a constructor that can be insert c;
chain called by return c.Id;
external client }
}
applications.
Web service
public class MyException extends
methods must
throw Throws an
Exception {} be defined in
exception, try { a global class.
signaling that Integer i;
an error if (i < 5)
has occurred throw new MyException();
} catch (MyException e) { while Executes a Integer count=1;
// Your MyException handling while (count < 11) {
// code here
block of code System.debug(count);
} repeatedly count++;
as long as }
a particular
Boolean
transient Declares transient integer currentValue; condition
instance remains true
variables that
cannot be
saved, and with sharing Enforces public with sharing class
SharingClass {
should not be sharing rules
// Code will enforce current
transmitted that apply to user's // sharing rules
as part of the the current }
view state, user. If
in Visualforce absent, code
controllers and is run under
extensions the default
system
context.

trigger Defines a trigger MyAccountTrigger on Account


(before insert, before update) {
trigger on an without Ensures that public without sharing class
if (Trigger.isBefore) {
sObject for (Account a : Trigger.old) { sharing the sharing noSharing {
// Code wont enforce the current
rules of // users sharing rules
if (a.Name != 'okToDelete') {
a.addError(
the current }
'You can\'t delete this user are not
record!'); enforced
}
}
}
virtual Defines public virtual class MyException
extends Exception {
a class or
// Exception class member
method // variable
true Identifies a Boolean mustIterate = true; that allows public Double d;
true value extension and
// Exception class constructor
assigned to overrides.
MyException(Double d) {
a Boolean You cant this.d = d;
override a }
method with
// Exception class method
the override
protected void doIt() {}
try in which try { keyword }
// Your code here unless the
you can
handle an } catch (ListException e) {
class or
exception if // List Exception handling code method has
one occurs // here been defined
} as virtual.
Apex Code Cheatsheet

Annotations Annotations continued


Keyword Description Example Annotation Description Example

@future Denotes global class MyFutureClass { @readOnly Denotes @readOnly


methods that @future
static void myMethod( methods that private void doQuery() {
}
are executed String a, Integer i) { can perform
asynchronously System.debug( queries
'Method called with: ' + a + unrestricted
' and ' + i);
// do callout, or execute by the number
// other long-running code of returned
} rows limit for a
} request

@isTest Denotes @isTest private class MyTest {


classes that // Methods for testing @remoteAction Denotes Apex @remoteAction
} global static String getId(
only contain controller
String s) {
code used for methods that }
testing your JavaScript code
application. can call from
These classes a Visualforce
dont count page via
against the JavaScript
total amount remoting. The
of Apex method must
used by your be static and
organization. either public or
global.

@isTest( Denotes a @isTest(OnInstall=true)


private class TestClass { Denotes a @restResource(urlMapping=
OnInstall=true) test class or @restResource
} '/Widget/*')
test method class that is
global with sharing class
that executes available as a MyResource() {
on package REST resource. }
installation The class must
be global. The
urlMapping
@isTest( Denotes a @isTest(SeeAllData=true) parameter is
private class TestClass { your resource's
SeeAllData=true) test class or
}
test method name and
that has is relative
access to all to https://
data in the instance.
organization, salesforce.
including com/services/
pre-existing apexrest/.
data that the
test didn't
create. The @httpGet, Denotes a @httpGet
default is false. global static MyWidget__c doGet()
@httpPost, REST method
{
@httpPatch, in a class }
@httpPut, annotated with
@deprecated Denotes @deprecated @httpDelete @restResource @httpPost
public void limitedShelfLife() { global static void doPost() {
methods, that the runtime
} }
classes, invokes when
exceptions, a client sends @httpDelete
enums, an HTTP GET, global static void doDelete() {
interfaces, or }
POST, PATCH,
variables that PUT, or DELETE
can no longer respectively.
be referenced
in subsequent The methods
releases of defined with
the managed any of these
package in annotations
which they must be global
reside and static.
Primitive Types Primitive Types continued
Annotation Description Example Annotation Description Example

Blob Binary data Blob myBlob = String Set of characters String s = 'repeating memes';
Blob.valueof('idea');
stored as surrounded by
a single object single quotes

Boolean Value that can Boolean isWinner = true; Object Any data String s = 'repeating memes';
only be assigned type that is
true, false, supported i
or null n Apex

Date Particular day Date myDate = Date.today(); Time Particular time Object obj = 10;
Date weekStart = // Cast the object to an integer.
myDate.toStartofWeek(); Integer i = (Integer)obj;
System.assertEquals(10, i);
Datetime Particular day Datetime myDateTime =
Datetime.now(); Object obj = new MyApexClass();
and time // Cast the object to the
Datetime newDateTime =
myDateTime.addMonths(2); // MyApexClass custom type.
MyApexClass mc = (MyApexClass)obj;
// Access a method on the
Decimal Number that Decimal myDecimal = 12.4567; // user-defined class.
Decimal divDec = myDecimal.divide
includes a mc.someClassMethod();
(7, 2, System.RoundingMode.UP);
decimal point. system.assertEquals(divDec, 1.78);
Decimal is
an arbitrary
precision Trigger Context Variables
number.
Variable Operators
Double 64-bit number Double d=3.14159;
that includes a isExecuting Returns true if the current context for the Apex code
decimal point. is a trigger only
Minimum value
-263. Maximum isInsert Returns true if this trigger was fired due to an insert
value of 263-1 operation

ID 18-character ID id='00300000003T2PGAA0'; isUpdate Returns true if this trigger was fired due to an update
Force.com operation
record identifier
isDelete Returns true if this trigger was fired due to a delete
Integer 32-bit number Integer i = 1; operation
that doesnt
include a isBefore Returns true if this trigger was fired before any record
decimal point. was saved
Minimum value
-2,147,483,648 isAfter Returns true if this trigger was fired after all records
maximum were saved
value of
2,147,483,647 isUndelete Returns true if this trigger was fired after a record was
recovered from the Recycle Bin
Long 64-bit number Long l = 2147483648L;
that doesnt new Returns a list of the new versions of the sObject
include a records.(This sObject list is available only in insert
decimal point. and update triggers. The included records can be
Minimum modified only in before triggers.)
value of -263
maximum value newMap A map of IDs to the new versions of the sObject
of 263-1. records. (Only available in before update, after
insert, and after update triggers.)
Object Any data Object obj = 10;
// Cast the object to an integer. old Returns a list of the old versions of the sObject
type that is
Integer i = (Integer)obj; records. (Only available in update and delete
supported in System.assertEquals(10, i); triggers.)
Ape
Object obj = new MyApexClass();
// Cast the object to the oldMap A map of IDs to the old versions of the sObject
// MyApexClass custom type. records. (Only available in update and delete
MyApexClass mc = (MyApexClass) triggers.)
obj;
// Access a method on the
// user-defined class. size The total number of records in a trigger invocation,
mc.someClassMethod(); both old and new.
Apex Code Cheatsheet

Collection Types Apex Data Manipulation


Annotation Description Example Language (DML) Operations
Annotation Description Example
List Ordered // Create an empty list
collection of of String Lead l = new Lead(Company='ABC',
insert Adds one or
typed primitives, List<String> myList = new LastName='Smith');
List<String>(); more records insert l;
sObjects,
myList.add('hi');
objects, or String x = myList.get(0);
collections that delete Deletes one Account[] webAccts = [SELECT Id,
are distinguished // Create list of records Name
from a query
or more FROM Account WHERE Name =
by their indices records
List<Account> accs = 'DotCom'];
[SELECT Id, Name FROM try {
Account LIMIT 1000]; delete webAccts;
} catch (DmlException e) {
// Process exception here
}

Map Collection of Map<String, String> List<Account> ls = new


merge Merges up to
key-value pairs MyStrings = List<Account>{
new Map<String, String>{
three records new Account(Name='Acme Inc.'),
where each of the same
a => b, c => new Account(Name='Acme')};
unique key maps type into one insert ls;
d.toUpperCase()};
to a single value. of the records, Account masterAcct = [SELECT Id,
A key can be any Account myAcct = new deleting the Name
primitive data FROM Account WHERE Name = 'Acme
Account(); others, and Inc.'
type, while a value Map<Integer, Account> m = re-parenting LIMIT 1];
can be a primitive, new Map<Integer, any related Account mergeAcct = [SELECT Id,
an sObject, a Account>(); records Name FROM
collection type, m.put(1, myAcct); Account WHERE Name = 'Acme'
LIMIT 1];
or an object. try { merge masterAcct mergeAcct;
} catch (DmlException e) {
}

Set Unordered Set<Integer> s = new undelete Restores Account[] savedAccts = [SELECT


collection Set<Integer>(); one or more Id, Name
s.add(12); FROM Account WHERE Name =
that doesnt records from 'Trump'
s.add(12);
contain the Recycle ALL ROWS];
System.assert(s.size()==1);
any duplicate Bin try { undelete savedAccts;
elements. } catch (DmlException e) {
}

update Modifies Account a = new


Account(Name='Acme2');
one or more insert(a);
existing Account myAcct = [SELECT Id,
records Name,
Standard Interfaces (Subset) BillingCity FROM Account WHERE
Name
= 'Acme2' LIMIT 1];
Database.Batchable myAcct.BillingCity = 'San
Francisco';
global (Database.QueryLocator | Iterable<sObject>) try {
start(Database.BatchableContext bc) {} update myAcct;
global void execute(Database.BatchableContext BC, } catch (DmlException e) {
list<P>){} }
global void finish(Database.BatchableContext BC){}
upsert Creates new Account[] acctsList = [SELECT Id,
Schedulable Name,
records and BillingCity FROM Account WHERE
global void execute(ScheduleableContext SC) {} updates BillingCity = 'Bombay'];
sObject for (Account a : acctsList)
Messaging.InboundEmailHandler records within {a.BillingCity = 'Mumbai';}
global Messaging.InboundEmailResult handleIn- Account newAcct = new Account(
a single Name = 'Acme', BillingCity =
boundEmail(Messaging.inboundEmail email, Messag- statement, 'San Francisco');
ing.InboundEnvelope env){} using a acctsList.add(newAcct);
specified try { upsert acctsList;
Comparable } catch (DmlException e) {
field to }
global Integer compareTo(Object compareTo) {} determine
the presence
of existing
objects, or
the ID field
if no field is
specified.
Commonly Used Methods Commonly Used Methods continued
System Class DescribeFieldResult Class
abortJob assert getByteLength getCalculatedFormula
assertEquals assertNotEquals getController getDefaultValue
currentPageReference currentTimeMillis getDefaultValueFormula getDigits
getInlineHelpText getLabel
debug enqueueJob
getLengthgetLocalName getName
equals getApplication getPicklistValues getPrecision
ReadWriteMode hashCode getReferenceTargetField getReferenceTo
isBatch isFuture getRelationshipName getRelationshipOrder
isScheduled nowprocess getScale getSOAPType
purgeOldAsyncJobs requestVersion getSObjectField getType
isAccessible isAutoNumber
resetPassword runAs
isCalculated isCascadeDelete
schedule scheduleBatch isCaseSensitive isCreateable
setPassword submit isCustom isDefaultedOnCreate
today isDependantPicklist isDeprecatedAndHidden
isExternalID isFilterable
Math Class isGroupable isHtmlFormatted
isIdLookup isNameField
abs acos asin atan atan2 cbrt isNamePointing isNillable
ceil cos cosh exp floor log isPermissionable isRestrictedDelete
isRestrictedPicklist isSortable
log10 max min mod pow random isUnique isUpdateable
rint round roundToLong signum sin isWriteRequiresMasterRead
sinh sqrt tan tanh Schema.DescribeFieldResult f =
Schema.SObjectType.Account.fields.Name;

DescribeSObjectResult Class
Limits Class
fields fieldSets
getChildRelationships getKeyPrefix getAggregateQueries getLimitAggregateQueries
getLabel getLabelPlural getAsyncCalls getLimitAsyncCalls
getLocalName getName getCallouts getLimitCallouts
getRecordTypeInfos getRecordTypeInfosByID getCpuTime getLimitCpuTime
getSobjectType isAccessible getDMLRows getLimitDMLRows
getDMLStatements getLimitDMLStatements
getRecordTypeInfosByName isCreateable
getEmailInvocations getLimitEmailInvocations
isCustom isCustomSetting
getFutureCalls getLimitFutureCalls
isDeletable isDeprecatedAndHidden
getHeapSize getLimitHeapSize
isFeedEnabled isMergeable
getMobilePushApexCalls getLimitMobilePushApexCalls
isQueryable isSearchable getQueries getLimitQueries
isUndeletable isUpdateable getQueryLocatorRows getLimitQueryLocatorRows
Schema.RecordTypeInfo rtByName = getQueryRows getLimitQueryRows
rtMapByName.get(rt.name); getQueueableJobs getLimitQueueableJobs
Schema.DescribeSObjectResult d = getSoslQueries getLimitSoslQueries
Schema.SObjectType.Account;

UserInfo Class
getDefaultCurrency getFirstName
getLanguage getLastName
getLocale getName
getOrganizationId getOrganizationName
getProfileId getSessionId
getTimeZone getUiTheme
getUiThemeDisplayed getUserEmail
getUserId getUserName
getUserRoleId getUserType
isCurrentUserLicensedq isMultiCurrencyOrganization
developer.salesforce.com

For other cheatsheets:


http://developer.salesforce.com/cheatsheets 10042016

S-ar putea să vă placă și