0% found this document useful (0 votes)
17 views311 pages

Developer PDF

Uploaded by

619maheshbagul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views311 pages

Developer PDF

Uploaded by

619maheshbagul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 311

Sr. No.

Syllabus Topic Teaching Hours Preparation Hours


1 Introduction to Apex Language
2 The architecture of language
2 Hours
3 Language basics
4 Debugging
5 Quiz & Assignment 3 Hours
6 Introduction to DML/SOQLstatements
7 Exception handling
2 Hours
8 with sharing/without sharing keyword
9 Transaction control statements
10 Quiz & Assignments 5 – 8 Hours
11 Querying Records in Salesforce using SOQL and 2 Hours
SOSL
12 Quiz & Assignments 3 – 5 Hours
13 Triggers in Salesforce 1 -2 Hours
14 Quiz & Assignments 3 Hours
Revision & Doubt Solving Session 1 Hour
Sr. No. Syllabus Topic Teaching Hours Preparation Hours
15 Salesforce Apex Code Best Practices 1 Hour
16 Visualforce – Overview & Architecture
17 Model - View - Controller
2 Hours
18 Visualforce Markup
19 Controllers
20 Global Variables
21 Quiz & Assignments 2 Hours
22 Visualforce – Overview & Architecture
23 Model - View - Controller
2 Hours
24 Visualforce Markup
25 Controllers
26 Global Variables
27 Quiz & Assignments 3 – 5 Hours
Revision & Doubt Solving Session 1 Hour
Sr. No. Syllabus Topic Teaching Hours Preparation Hours
28 Custom Labels
29 TranslationWorkbench
1 Hour
30 Custom Settings
31 Custom MetadataType
32 Quiz & Assignments 3 Hours
33 Batch Apex
34 Scheduled Apex
2 Hours
35 Future Methods
36 Queueable Apex
37 Quiz & Assignments 2 Hours
38 What are Web Services?
39 Types of Web Services
1 Hour
40 Some Basic Terminologies Creating Apex
41 REST Web Services
Revision & Doubt Solving Session 1 Hour
Sr. No. Syllabus Topic Teaching Hours Preparation Hours
42 Performing HTTP Callouts 1 Hour
43 Writing Unit Tests
44 Quiz & Assignments
45 Web Services in Salesforce using SOAP 1 Hour
46 Quiz & Assignments 3 Hours
47 Introduction to Lightning Components 1 Hour
48 Invoking Apex from Lightning Component
49 Standard Lightning Component
50 Lightning Out 2 Hours
51 LDS
52 Debugging in Lightning Component
53 Best Practices
Revision & Doubt Solving Session 1 Hour
Sr. No. Syllabus Topic Teaching Hours Preparation Hours
54 Inter-component Communication
55 Communication Patterns
1 Hour
56 Event Life-cycle
57 Locker Service
58 Why to Follow Best Practices?
59 How to Write Good VF Pages
60 Tips for Writing JavaScript and CSS in Pages Best 1 Hour
61 Practices for Lightning Components
62 Tips for Migrating from VF Pages to Lightning
63 Conclusion
Overall Revision 3 – 5 Hours
Total Hours – ( 40 – 45 Hours) 22 – 25 Hours 15 – 20 Hours
Salesforce.com Training
Developer Module
Programming in Salesforce using Apex
Part I
Created By – Nanostuffs Team
Agenda 2

Introduction to Apex Language

The architecture of language

Language basics

Debugging
Topics 3

What is Apex? Naming Conventions

Differences Between Apex Classes and Java Access Modifiers


Classes
Expressions/ Assignment Statements/
Multi-tenancy and Programming Languages Conditional (If-Else) Statements

Loops
Classes, Objects and Interfaces
Invoking Apex
Interfaces and Extending Classes
How Does Apex Work?
Language Constructs
What is the Apex Development Process?

Data Types
When Should I Use Apex?

Variables What are the Limitations of Apex?


What is Apex? 4

“Apex is the world's first on-demand programming language”

Apex is a strongly-typed, object-oriented programming language.

Allows developers to execute flow and transaction control statements


on the Force.com platform server in conjunction with calls to the
Force.com API.
Uses syntax that looks like Java and acts like database stored
procedures.

Allows developers to add business logic to most system events,


including button clicks, related record updates, and Visualforce pages.

Apex scripts can be initiated by Web service requests and from triggers
on objects.
How does Apex work? 5

When a developer writes and saves an Apex script to the platform -

• The platform application server first compiles the code into an abstract setof
instructions that can be understood by the Apex runtime interpreter and
• Then saves those instructions as metadata.
Apex runs entirely on-demand on the Force.com platform, as shown in the
following architecture diagram.

Force.com Platform

Uncompiled Application Compiled


Apex Server Apex

Developer
User Internet Apex
Request Metadata

Request Apex
Runtime
Result Interpreter Compiled
End
User Apex
Apex is: 6

Integrated
• Data manipulation language (DML) calls.
• Inline SOQL and SOSL.
• Looping allows bulk processing of multiple records at a time.
• Locking syntax prevents record update conflicts.
• Custom public Force.com API calls can be built from stored Apex
methods.
• Warnings and errors issued when a user tries to edit or delete a
custom object or field that is referenced by Apex.
Easy to use
• Data focused.
• Apex is designed to thread together multiple query and DML
statements into a single unit of work on the Force.com platform
server similar to stored procedures.
Apex is: 7

Rigorous
• Apex is a strongly-typed language that uses direct
references to schema objects such as object and field
names.
• It fails quickly at compile time if any references are
invalid, and stores all custom field, object, and class
dependencies in metadata to ensure they are not
deleted while required by active Apex scripts.

Hosted
• Apex is interpreted, executed, and controlled entirely
by the Force.com platform.
Multitenant Platforms 8
Multitenant Platforms 9

Multitenant Aware
• Like the rest of the Force.com platform, Apex runs in a multitenant environment.
• Apex runtime engine is designed to guard closely against runaway scripts, preventing
them from monopolizing shared resources.
• Any scripts that violate these limits fail with easy-to-understand error Messages.

Automatically Upgradeable
• Apex never needs to be rewritten when other parts of the Force.com platform are
upgraded.
• Because the compiled code is stored as metadata in the platform, it always gets
automatically upgraded with the rest of the system.

Easy to Test
• Apex provides built-in support for unit test creation and execution, including test
results that indicate how much code is covered, and which parts of your code could be
more efficient.
• Salesforce.com ensures that scripts always work as expected by executing all unit tests
stored in metadata prior to any platform Upgrades.
Classes, Objects & Interfaces 10

A class is a template or blueprint from which Apex


objects are created.

Classes consist of other classes, user-defined


methods, variables, exception types, and static
initialization code.

They are stored in the application under Setup


➤Develop ➤ Apex Classes
Classes, Objects & Interfaces 11

Apex Defining Classes

• In Apex, you can define top-level classes (also called


outer classes) as well as inner classes, that is, a class
defined within another class.
For example:
public class MyOuterClass{
//Additional MyOuterClasscodehere
class MyInnerClass{
//MyInnerClass codehere
}
}
Interfaces & Extending Classes

An interface is like a class in which none of the


methods have been implemented.

The method signatures are there, but the body of


each method is empty.

To use an interface, another class must implement it


by providing a body for all of the methods contained
in the interface.
Interfaces & Extending Classes 13

Interfaces can provide a layer of abstraction to your code.

They separate the specific implementation of a method from the


declaration for that method.

This way you can have different implementations of a method based on


your specific application.

public clas
public interface Purcha
Double discount();
}
}
Extending virtual Classes 14

Use virtual Keyword at class level to allow a class to be extended by


another class

Use virtual keyword at method level to allow that method to override


in its derived class.

public vi r t u a l class CustomerPurchaseOrder {


public vi r t u a l Double discount(){
return .05; }
}

/ / different discount
public class EmployeePurchaseOrder extends CustomerPurchaseOrder
{
public override Double discount()
{
return .10; / / I t ’ s worth i t being an employee! 10%discount
}
}
Extending Abstract classes

Define class with abstractkeyword

Define methods in it as abstract

Abstract method does not have method body. It just has method
signature
Interfaces & Extending Classes 16

/ / One implementation o f the in t e r f a c e f o r customers


public v i r t u a l class CustomerPurchaseOrder implements PurchaseOrder
{
public v i r t u a l Double discount()
{
return . 0 5 ;
}
}
/ / d i f f e r e n t discount
public class EmployeePurchaseOrder extends CustomerPurchaseOrder
{
public override Double discount()
{
return . 1 0 ; / / I t ’ s worth i t being an employee! 10%discount
}
}
Language Constructs 17

SOQL and
Data
Expressions SOSL
Types
Queries

Exception
Variables Loops
Statements
Data Types 18

In Apex, all variables and expressions have a data type that is one of the following:

A primitive
Such as an Integer, Double, Decimal, Long, Date, Datetime, String, ID, or
Boolean, Blob.

sObjects

An sObject, either as a generic sObject or as a specific sObject, such as


an Account, Contact, or MyCustomObject c.

Objects created from user-definedApex classes

Wrapper Class
Data Types 19

Objects created from system suppliedApex classes

Collection
• Lists
• A list is an ordered collection of typed primitives, sObject,Apex
objects or collections that are distinguished by their indices.
• Sets
• A set is an unordered collection of primitives that do not contain any
duplicate elements.
• Maps
• A map is a 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 Apex object.
Variable Initialization 20

p u b l i c class AccountHandler{

//Memory would be allocated t o the va riable with a ' n u l l ' value


Integer resetCounter;

//Memory would be allocated to the vari a b l e with a value = 0


Integer c o n I t er at or = 0 ;

/* A common p i t f a l l i s t o assume t h a t an u n i n i t i a l i z e d
bool ean var i abl e i s i ni t i al i zed t o f al se by t he syst em.
This i s n ’ t the case. Like a l l other v a r i a b l e s ,
boolean variables are n u l l i f not assigned a value e x p l i c i t l y. * /
Boolean i s A c t i v e ;
Boolean isNonEditable = f a l s e ;
}
sObject Data Types and Type casting 21

An sObject variable represents a row of data and can only be declared in Apex using the
Web Services API name of the object.
• For example:
• Account a = new Account();
• MyCustomObject__c co = new MyCustomObject__c();
Apex allows the use of the generic sObject abstract type to represent any object. The
sObject data type can be used in code that processes different types of sObjects.
• For example:
• sObject s = newAccount();

Use casting between the generic sObject type and the specific sObject type.

• For example:
// Cast the generic variables from the example above
// into a specific account and account variable a
Account a = (Account)s;
// The following generates a runtime error
Contact c = (Contact)s;
Id Data Types 22

The ID of an sObject is a
read-only value and can The Force.com platform
never be modified assigns ID values
explicitly in Apex unless automatically when an
it is cleared during a object record is initially
clone operation, or is inserted to the database
assigned with a for the first time.
constructor.
Variables 23

Case Sensitivity
• To avoid confusion with case-insensitive SOQL and SOSL
queries, Apex is also case-insensitive.
• Variable and method names are case insensitive.
• For example:
Integer I; //Integer i; This would not be an error.
• References to object and field names are case insensitive.
• For example:
Account a1;
ACCOUNT a2;
• SOQL and SOSL statements are case insensitive.
• For example:
Account[] accts = [sELect ID From ACCouNT where nAme
= 'fred'];
Variables

Constants

• Constants can be defined using the Final


keyword
• It means the variable can be assigned at
most once, either in the declaration itself
or with a static initializer method if the
constant is defined in a class.
• For example:
static final Integer PRIVATE_INT_CONST2
= 200;
Access Modifiers 25

• This is the default, and means that the method or


variable is accessible only within the Apex class in
which it is defined.
• If you do not specify an access modifier, the method
private or variable is private.

• This means that the method or variable is visible to


any subclasses in the defining Apex class.
• You can only use this access modifier for instance
methods and member variables.
protected • Note that it is strictly more permissive than the
default (private) setting, just like Java.
Access Modifiers 26

• This means the method or variable can be used by any


Apex in this application or namespace.
public

• This means the method or variable can be used by any


Apex script that has access to the class, not just the Apex
scripts in the same application.
• This access modifier should be used for any method that
global needs to be referenced outside of the application, either in
the Force.com Web Services API or by other Apex scripts.
Expressions/Assignment Statements/Conditional (If-Else) Statements 27

An expression is a construct made up of variables, operators, and method


invocations that evaluates to a single value.

e.g. Integer sum = number1 + number2;

A literal expression.

• For example:
1+1

A new sObject, Apex object, list, set, or map.

• For example:
new Account(<field_initializers>)
new List<Account>()
new Set<String>{}
new Map<String, Integer>()
Expressions/Assignment Statements/Conditional (If-Else) Statements 28

Any value that can act as the left-hand of an assignment operator (L-
values), including variables, one-dimensional list positions, and most
sObject or Apex object field references.
• For example:
• Integer i
• myList[3]
• myContact.name

An assignment statement is any statement that places a value into a


variable.

• For example:
• Integer i = 1;
• Account a = new Account();
• Account[] accts = [select id from account];
Loops 30

Do-While
Loops

SOQL For While


Loops Loops

Loops

List or Set
Iteration For Loops
For Loops

Traditional
For Loops
Invoking Apex 31

Triggers

Custom
Anonymous
Buttons &
Blocks
Links

Invoking
Apex
SOAP and
AJAX
REST
Toolkit
Services
Through
Visualforce
Pages
Static and Instance 32

In Apex, you can have static methods, variables, and initialization


code, instance methods, member variables, and initialization code
(which have no modifier), and local variables.

Static methods, variables, or initialization code are associated with


a class, and are only allowed in outer classes.

When you declare a method or variable as static, it is initialized only


once when a class is loaded.

Instance methods, member variables, and initialization code are


associated with a particular object and have no definition modifier.
Static and Instance 33

When you declare instance methods, member


variables, or initialization code, an instance of that
item is created with every object instantiated from
the class.

Local variables are associated with the block of


code in which they are declared.

All local variables should be initialized before they


are used.
Apex Keywords 34

instanceof

• If you need to verify at runtime whether an object is actually an


instance of a particular class, use the instanceof keyword.
• The instanceof keyword can only be used to verify if the target type in
the expression on the right of the keyword is a viable alternative for the
declared type of the expression on the left.

transient

• Use the transient keyword to declare instance variables that cannot be


saved and shouldn't be transmitted as part of the view state for a
Visualforce page.
Apex Keywords 35

final
• Final variables can only be assigned a value once, either when you declare a
variable or in initialization code.
• You must assign a value to it in one of these twoplaces.
• Static final variables can be changed in static initialization code or where
defined.
• Member final variables can be changed in initialization code blocks,
constructors, or with other variable declarations.
• To define a constant, mark a variable as both static and final.
• Non-final static variables are used to communicate state at the class level
(such as state between triggers).
• However, they are not shared across requests.
• Methods and classes are final by default.
• You cannot use the final keyword in the declaration of a class or method. This
means they cannot be overridden.
• Use the virtual keyword if you need to override a method or class.
Apex Keywords 36

this

• You can use the this keyword in dot notation, without parenthesis, to represent
the current instance of the class in which itappears.
• Use this form of the this keyword to access instance variables and methods.
• You can use the this keyword to do constructor chaining, thatis, in one
constructor, call another constructor.
• In this format, use the this keyword with parentheses.
• public class testThis
{
// First constructor for the class. It requires a string parameter.
public testThis(string s2) { }
// Second constructor for the class. It does not require a parameter.
// This constructor calls the first constructor using the this keyword.
public testThis() { this('None'); }
}
Apex Keywords 37

super

• You can use super keyword in constructor of derived class to call the constructor of
base class.
Differences between Apex & Java classes 39

Inner classes and interfaces can only be declared one


level deep inside an outer class.

Static methods and variables can only be declared in a


top-level class definition, not in an inner class.

Inner classes behave like static Java inner classes, but


do not require the static keyword.

Inner classes can have instance member variables like


outer classes, but there is no implicit pointer to an
instance of the outer class (using the this keyword).
Differences between Apex & Java classes 40

The private access modifier is the default, and means that


the method or variable is accessible only within the Apex
class in which it is defined.

Specifying no access modifier for a method or variable and


the private access modifier are synonymous.

The public access modifier means the method or variable


can be used by any Apex in this application or namespace.

The global access modifier means the method or variable


can be used by any Apex script that has access to the class,
not just the Apex scripts in the same application.
Differences between Apex & Java classes 41

This access modifier should be used for any method that needs to be
referenced outside of the application, either in the Force.com Web
Services API or by other Apex scripts.

If you declare a method or variable as global, you must also declare the
class that contains it as global.

Methods and classes are final by default.

• The virtual definition modifier allows extension and overrides.


• The override keyword must be used explicitly on methods that override
base class methods.

Interface methods have no modifiers—they are always global.


Quiz 42

What are access specifiers in Apex?

Write a syntax to declare a constant variable in Apex.

Which Apex keyword is used to ensure that the declared instance variables cannot be saved
and transmitted as a part of the view state in a Visualforce page?

State whetherTrue/False:

• Classes and methods can be declared as static


• Classes and methods can be declared as final
• Apex does not give us a method or keyword to identify the type at run
time
Programmatic Model 1
*In addition to all the Trailhead assignments
Apex Basics -

1. Write a method that accepts integer parameters and builds and prints an array of up to that integer
parameter.
(For example: If your method accepts (integer) 5 as a parameter then build an array of any datatype but array size
should be the accepted parameter so in this case, your array size should be 5 )
2. Method which will accept an array of integers as parameters write a code to
a. Sort the array in ascending order
b. Sort the array in descending order
c. Print the Maximum number in the array
d. Print the Minimum number in the array
e. Print duplicates and their occurrences in the array. For ex: if the array is [2,2,3,4,4,5] then your output will be
as follows:

Number: Appearance 2: 2
3: 1
4:2
5 :1
3. Method which will calculate the simple interest (Accept necessary parameters)
Salesforce.com Training
Developer Module
Programming in Salesforce using Apex
Part II
Created By – Nanostuffs Team
Agenda 2

Introduction to DML/SOQL statements

Exception handling

with sharing/without sharing keyword

Transaction control statements


Data Types 4

DML operations work on variables declared as the generic sObject data


type as well as with regularsObjects.

sObject variables are initialized to null, but can be assigned a valid object
reference with the newoperator.

• For example:
• Account a = newAccount();

Developers can also specify initial field values with comma-separated


name = value pairs when instantiating a new sObject.

• For example:
• Account a = new Account(name = 'Acme', billingcity = 'San Francisco');
Accessing sObject Fields 7

If you use the generic sObject type, instead of a specific


object such as Account, you can only access the ID field.

• For example:
DML operations 8

Need all the


Need all the required fields
required fields Only need record
populated with Id
populated record Id

Insert records Update records Delete records

Either need AllorNone flag for


Record Id or performing Partial
External Id DML Operations

Upsert records DML Operationsusing


Database classes
SOQL Queries 9
Accessing sObject Fields through Relationships 10

sObject records represent relationships to other


records with two fields an ID and an address that
points to a representation of the associated sObject.

• For example:
• The Contact sObject has both an AccountId
field of type ID and an Account field of type
Account that points to the associated sObject
record itself.
Accessing sObject Fields through Relationships 11

The reference field is only populated as the result of a SOQL or SOSL


query.
• For example:
The following Apex script shows how an account and a contact can be
associated with one another, and then how the contact can be used
to modify a field on the account:
Accessing sObject Fields through Relationships 12

The expression c.account.name, as well as any other


expression that traverses a relationship, displays slightly
different characteristics when it is read as a value than
when it is modified.
• When being read as a value, if c.account is null, then
c.account.name evaluates to null, but does not yield a
NullPointerException.
• This design allows developers to navigate multiple
relationships without the tedium of having to check for
null values.
• When being modified, if c.account is null, then
c.account.name does yield a NullPointerException.
Accessing sObject Fields through Relationships 13

The sObject field key can be used with insert, update, or upsert to
resolve foreign keys by externalID.
• For example:

• This inserts a new contact with the AccountId equal to the account with
the external_id equal to ‘12345’.
• If there is no such account, the insert fails.

The following code is equivalent to the previous code. However, because it


uses a SOQL query, it is not as efficient.
• Code:
Validating sObjects and Fields 14

The platform prevents users from


making the following types of
When an Apex script is parsed and modifications when thosechanges
validated, all sObject and field cause an Apex script to become
references are validated against invalid:
actual object and field names, • Changing a fieldor object name
and a parse-time exception is
• Convertingfrom one data type
thrown when an invalid name is to another
used.
Exception Handling in apex

Apex provides exception handling using try catch blocks similar toJava

You can catch generic exception as well as pre-defined exceptions or custom


exception

You can create custom exception classes in apex

Syntax
With Sharing/Without Sharing Keyword 16

• Apex generally runs in system context; that is, the current user's permissions, field-
• level security, and sharing rules aren’t taken into account during code execution.

• Because these rules aren't enforced, developers who use Apex must take care that
they don't inadvertently expose sensitive data that would normally be hidden from
users by user permissions, field-level security, or organization-wide defaults.

• Use keyword with Sharing to enforce sharing rule while making SOQL queries in Apex
so that query would return only those records to which are shared to current user

• Use keyword without sharing to not enforce sharing rule while making SOQL queries
in Apex
With Sharing/Without Sharing Keyword

If no sharing keyword is specified it runs in without sharing


mode means it does not enforce any sharing rules

The behavior of Apex methods in a class that does not have


any sharing keyword
Transaction control statements

What is Savepoints?

What is Rollback?

If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated,
the later savepoint variables become invalid. For example, if you generated savepoint SP1 first, savepoint SP2
after that, and then you rolled back to SP1, the variable SP2 would no longer be valid. You will receive a
runtime error if you try to use it.

Each savepoint you set counts against the governor limit for DML statements.

Each rollback counts against the governor limit for DML statements
Transaction control statements example 19
Apex Development Process

All classes
and triggers
Every trigger compile
has some test successfully.
75% of code coverage.
coverage of
Deploying Apex scripts
Your Apex to by unit tests
Write your a Salesforce is essential.
Apex scripts. Sandbox/
First obtain a Production
Developer Organization.
Edition
account.
When do we use Apex? 21

To Attach business logic to


another operation, such as saving
a record, so that it occurs
To Process more than one record whenever the operation is
at a time efficiently. executed, regardless of whether
it originates in the user interface,
a Visualforce page, or from the
Web Services API.
Apex Features & Functionality 22

Transaction Control
• Apex Code is closely bound to Force.com data, developers can readily
add transactional features to their applications.
• For example, if one user is referencing a field while somebody else is
trying to delete it, the system is aware of the conflict.
• Apex Code also features data commits and rollbacks, which are
especially important when working across multiple objects.

Packaging, Re-use and Web Services


• Apex Code uses a packaging model similar to that of Java, in which
reusable packages of code can be invoked from each other or from
within triggers.
• Unlike Java, however, Apex is not object oriented in the sense that
those packages can be modified through inheritance.
Apex Features & Functionality 23

Performance, Scalability and Upgrades

• Apex Code runs on demand, scalability, compatibility and


maintenance issues are Salesforce.com's responsibility, not yours.
• Apex-developed applications can scale indefinitely to support
additional users, without your having to deploy additional servers.
• Applications potentially run faster because a single query can obtain
information from multiple objects.

Apex Code and the AppExchange

• Apex Code can be packaged alongside custom objects, S-controls and


other platform features, allowing developers to redistribute their
Apex Code-enhanced apps via the AppExchange.
Limitations of Apex 24

Apex cannot be used for:

Change standard functionality — Apex can only


prevent the functionality from happening, or add
additional functionality.

Create temporary files.

Spawn threads.
Governor Limits Best Practices 25

Bulkify Code: Make your Code to Work for more than one record at a time.
• Bad Code
trigger accTrggr on Account (before insert, before update)
{
//This only handles the first record in the Trigger.new collection
//But if more than one Account initiated this trigger, those additional records
//will not be processed
Account acct = Trigger.new[0];
acct.Description = acct.Name + ':' + acct.BillingState;
}
• Correct Code
trigger accTrggr on Account (before insert, before update)
{
List<String> accountNames = new List<String>{};
//Loop through all records in the Trigger.new collection
for(Account a: Trigger.new)
{
//Concatenate the Name and billingState into the Description field
a.Description = a.Name + ':' + a.BillingState;
}
}
Governor Limits Best Practices 26

Avoid SOQL Queries inside FOR Loops: Move SOQL Queries outside FOR
Loop

• Bad Code
Governor Limits Best Practices 27

• Good Code
Quiz

Which are the DML statements supported byApex?

What is upsert operation?

What is the return type of SOQL query?

What is the difference between with sharing and without sharing?

What do you mean by Save points & roll back?


Assignment -
Advanced concepts / Collections/SOQL Queries/DML Operations
1. Query on Account object/ records and show/print each account record using:
a. Traditional for loop
b. Advanced for loop
c. While loop
2. Implement the following Searching algorithm using Apex & Collections -
a. Binary Search
b. Linear Search
3. Implement any four Sorting algorithms using Apex & Collections -
a. Bubble Sort
b. Insertion Sort
c. Merge Sort
d. Quick Sort
e. Bucket Sort
f. Selection Sort
4. Create an Account Record with Name = “Nanostuffs”. Create associated contacts. Create a Custom field called Contact Count
on Account. Query on Contact where Account. Name = “Nanostuffs” and count the associated contacts. Update the custom
field on Accounts with that count. -
5. Write an SQOL Query to show the Child-Parent relationship and print the result. For example, Account is a parent and
Contact is a child. Then Query on Child -
6. State the difference between Database methods for DML and basic DML statements.
Salesforce.com Training
Developer Module
Querying Records in Salesforce
using SOQL and SOSL
Created By – Nanostuffs Team
What Is SOQL? 2

• Used to build queries for fetching data on the Force.com platform.

• Designed specifically for Salesforce data.

• Similar to SQL which differs from SQL in terms of the data model and query
joins.

• SOQL allows you to specify the source object (such as Account), a list of fields
to retrieve, and conditions for selecting rows in the source object.
Purpose Of SOQL 3

The main purpose of SOQL is to fetch data from Salesforce objects. SOQL can
be used in the following environments:

• The query String parameter in the query() call


• Apex statements
• Visualforce controllers and the getter methods
• The schema explorer of the Force.com IDE
SOQL Syntax 4

Similar to SQL, SOQL also makes use of the SELECT statement to fetch data.
Let us explore the following SOQLsyntax:

SELECT fieldList [subquery][...]


FROM objectType[,...]
[ WHERE conditionExpression]
[ GROUPBY{fieldGroupByList|ROLLUP (fieldSubtotalGroupByList)|CUBE
(fieldSubtotalGroupByList)}
[ HAVING havingConditionExpression] ]
[ ORDERBY fieldOrderByList {ASC|DESC} [NULLS {FIRST|LAST}] ]
[ LIMIT numberOfRowsToReturn]
[ OFFSET numberOfRowsToSkip]
SOQL Syntax – WHERE Clause 5

You can add multiple field expressions to a condition expression by using logical
operators:

[ SELECT Id, Name, toLabel(RecordType.Name)


FROM Contact
WHERE cName =: contactName
AND (EmailOptOut = FALSE
OR ActivityDate__c != null)
AND Designation__c INCLUDES ('CEO', 'Manager', 'Architect’)]

[ SELECT Id
FROM Event
WHERE What.Type IN ('Account', 'Opportunity')]
The Comparison Operators 6

• Comparison operators are used in SOQL to compare a value with another


value to return true or false.
Sequence Name Description
= Equals
!= Not equals
<, <= Less than or Less than equal to
>,>= Greater than or Greater than equal to
INCLUDES, EXCLUDES Applies onlyto multi-select picklists
LIKE Expression is true if the value in the specified field name matches
the characters of the text string in the specified value
IN If the value equals any one of the specified values in a WHERE
clause
NOT IN If the value does not equal any of the specified values in a WHERE
clause
The Logical Operators 7

• Used in the field expression of the WHERE clause in a SOQLquery.


• Connectors for connecting one or more conditions inside a single SOQL
statement.
• Returns either true or false.

Logical operators in SOQL:


• AND
• OR
• NOT
The Escape Sequences 8

• An escape character is a character that invokes an alternative interpretation of


the subsequent characters in a character sequence.
Sequence Name Description
\n or \N New line
\r or \R Carriage return
\t or \T Tab
\f or \F Form feed
\b or \B Bell
\" One double-quote character
\' One single-quote character
\\ Backslash
LIKE operator expression: \_ Matches a single underscore character (_)
LIKE operator expression: \% Matches a single % sign character(%)
The Date Formats 9

• When querying the records using the date field or the date and time field in the
SOQL statement, the date formats should be followed.

Format Format Syntax Example

Date only YYYY-MM-DD 1999-01-01

Date, time, and time zone •YYYY-MM- • 1999-01-01T23:01:01+01:00


offset DDThh:mm:ss+hh:mm • 1999-01-01T23:01:01-08:00
•YYYY-MM-DDThh:mm:ss- • 1999-01-01T23:01:01Z
hh:mm
•YYYY-MM-DDThh:mm:ssZ
The Date Literals 10

• When querying the records using the date field in the SOQL statement, the
date literals can be used.

Date Literal Range Example


TODAY Starts 00:00:00 of the current day and continues for SELECT Id FROM Account WHERE
24 hours. CreatedDate> TODAY
LAST_WEEK Starts 00:00:00 on the first day of the week before SELECT Id FROM Account WHERE
the most recent first day of the week andcontinues CreatedDate> LAST_WEEK
for seven full days. Your locale determines the first
day of the week.
NEXT_MONTH Starts 00:00:00 on the first day of the month after SELECT Id FROM Opportunity
the month that the current day is in and continues WHERE CloseDate =
for all the days of thatmonth. NEXT_MONTH
Filtering Multiselect Picklist Values 11

The INCLUDES and EXCLUDES operators are used to filter the multiselect
picklist field.

SELECT Employee_Name__c, Skills c


FROM Employee__c
WHERE Skills c INCLUDES ('C', 'C#’)

The preceding query will fetch the names of all the employees whose Skills
match either with C or C#.
SOQL Syntax – The ORDER BY Clause 12

• The ORDER BY clause in SOQL is used to sort the records retrieved in the
ascending or descending order.
• There is no guarantee of the order of results unless you use an ORDER BY
clause in a query.

• An ascending order sample query is given as follows:


SELECT Name, Amount
FROM Opportunity
ORDER BY Name ASC
SOQL Syntax – The ORDER BY Clause 13

Factors affecting results returned by ORDER BY:

• Sorting is case sensitive.


• Order by compatible with relationship syntax
• Multiple column sorting is supported

Limitations:

• Unsupported datatypes –multiselect-picklist, rich text area, long text area and
encrypted fields.
SOQL Syntax – The GROUP BY Clause 14

You can use the GROUP BY option in a SOQL query to avoid iterating through
individual query results.

You specify a list of fields to group the query results

• Syntax :
[GROUP BY fieldGroupByList]

• Example:

SELECT LeadSource
FROM Lead
GROUP BY LeadSource
SOQL Syntax – The HAVING Clause 15

HAVING is an optional clause that can be used in a SOQL query to filter results
that aggregate functions return

The HAVING clause is used to specify the search condition in the GROUP BY
clause or the aggregate functions.

Example:

SELECT City c, COUNT(Employee_Name c)


FROM Employee__c
GROUPBY City__c
HAVING COUNT(City c)
Aggregate Functions 16

• Aggregate functions allow you to roll up and summarize your data in a query.
• e.g. AVG(), COUNT(), MIN(), MAX(), SUM(), and more.

• However, these functions become a more powerful tool to generate reports


when you use them with a GROUP BY clause.

• For example, you could find the average ‘Amount’ for all your opportunities by
campaign :
SELECT CampaignId, AVG(Amount)
FROM Opportunity
GROUP BYCampaignId
Relationship Queries 17

• Relationship queries are similar to SQL joins

• There must be a parent-to-child or child-to-parent relationship connecting the


objects

• Parent-to-child and child-to-parent relationships exist between many types of


objects. For example, Account is a parent of Contact.
Relationship Queries 18

• For child-to-parent relationships, the relationship name to the parent is the


name of the foreign key, and there is a relationship Name property that holds
the reference to the parent object.

• These relationships are traversed by specifying the parent using dot notation
in the query.

SELECT FirstName, Account.Name


FROM Contact
WHERE Account.Name LIKE 'C%'
Relationship Queries 19

• For parent-to-child relationships, the parent object has a name for the child
relationship that is unique to the parent, the plural of the child object name.

• These relationships can be traversed only in the SELECT clause, using a


nested SOQL query.

SELECT Name,
(SELECT FirstName, LastName FROM Contacts)
FROM Account
Semi Joins 20

• Semi Join: Returns rows from first table where one or more matches are found
in second table. Use IN operator.

• Example:

SELECT Id, Name


FROM Account
WHERE Id IN ( SELECT AccountId
FROM Opportunity
WHERE OpportunityStage = 'Closed Lost’)
Anti Joins 21

• Anti Join: Returns rows from first table where no matches are found in the
second table. Use NOT IN operator.

• Example:

SELECT Id, Name


FROM Account
WHERE Id NOT IN (SELECT AccountId
FROM Opportunity
WHERE IsClosed = false)
Semi Joins and Anti Joins – Reference Field 22

• Semi Join:
SELECT Id
FROM Task
WHERE WhoId IN ( SELECT Id
FROM Contact
WHERE MailingCity = ' LA')

• Anti Join:
SELECT Id, Amount
FROM Opportunity
WHERE AccountId NOT IN (SELECT AccountId
FROM Contact
WHERE LeadSource = ' Web')
Multiple Semi Joins and Anti Joins 23

• Multiple Join:

SELECT Id, Name


FROM Account
WHERE Id IN (SELECT AccountId
FROM Contact
WHERE LastName LIKE 'apple%' )
AND Id IN (SELECT AccountId
FROM Opportunity
WHERE isClosed = false )
Limitations 24

Main Query Limitations

• No more than two IN or NOT IN statements per WHERE clause.


• The left operand must query a single ID(primary key) or reference (foreign
key) field.
• The left operand cannot have more than one level of relationships
Example:
SELECT Id, Name
FROM Contact
WHERE Account.Id IN (SELECT AccountId
FROM Opportunity
WHERE OpportunityStage = 'Closed Lost’)
Semi Joins and Anti Joins - Limits 25

Subquery Limits
• A subquery must query a field referencing the same object type as the main
query.
• There is no limit on the number of records matched in a subquery. Standard
SOQL query limits apply to the mainquery.
• The selected column in a subquery must be a foreign key field, and cannot
traverse relationships.
• You cannot query on the same object in a subquery as in the main query.
• You cannot use subqueries with OR.
• COUNT, FOR UPDATE, ORDER BY, and LIMIT are not supported in
subqueries.
• You cannot nest a semi-join or anti-join statement in another semi-join or anti-
join statement.
SOQL Syntax –The OFFSET Clause 26

• The OFFSET clause is used to specify the starting row number from which the
records will be fetched.

• A sample query is given as follows:


SELECT Name
FROM Account OFFSET 100

• The OFFSET clause along with LIMIT is useful in retrieving a subset of the
records or implementing pagination.

• Consideration: The maximum offset is 2,000 rows


When to useSOQL 27

We can use SOQL in the following situations:


• When we know the object in which we have our required data
• When we want to fetch data from multiple objects with a lookup or master-
detail relationship
• To have the data set in a sorted manner
• To summarize the data
• To limit our data while retrieving it

For indexing, the following fields can be used in SOQL:


• Id can be used as the primary key.
• Lookup or master-detail relationship fields can be used as the foreign key.
• The custom fields can be used as the external IDs.
What Is SOSL? 28

Use the Salesforce Object Search Language (SOSL) to search your


organization’s Salesforce data for specific information.

• You can search text, email, and phone fields multiple objects—including
custom objects—that you have access to in a single query.

• SOSL allows you to specify the following for source objects:


1. text expression
2. scope of fields to search
3. list of objects and fields to retrieve
4. conditions for selecting rows in the source objects
What Is SOSL? 29

• The SOSL query start with the keyword ‘FIND’.

• The result of SOSL is a list of lists of sObjects “List<List<sObject>>”.

• The returned result contains the list of sObjects in the same order as order
mentioned in SOSL query

• If a SOSL query does not return any records for a specified sObject type, then
search results include an empty list for that sObject.
SOSL Example 30

• SOSL statements evaluate to a list of lists of sObjects, where each list


contains the search results for a particular sObject type.
• Here's an example that searches all field across all Account and Lead
sObjects.

• Execute the following:


List<List<SObject>> searchList =
[ FIND ‘Joe*’ IN ALL FIELDS RETURNING Account (Id, Name), Lead];

Account[] accList = ((List<Account>)searchList[0]);


Lead[] leadList = ((List<Lead>)searchList[1]);
Apex DML Operations 31

• You can perform DML operations using the Apex DML statements or the
methods of the Database class.
• For lead conversion, use the convertLead method of the Database class.
There is no DML counterpart for it.
• Use Data Manipulation Language (DML) statements to insert, update, merge,
delete, and restore data in Salesforce.
• The following Apex DML statements are available:
1. Insert
2. Update
3. Upsert
4. Delete
5. Undelete
6. Merge
Insert Statement 32

• The insert DML operation adds one or more sObjects, such as individual
accounts or contacts, to your organization’s data.
• Insert is analogous to the INSERT statement in SQL.
• Syntax
• insert sObject
• insert sObject[]

• The following example inserts an account named 'Acme':


Account newAcct = new Account(name = 'Acme’);
try {
insert newAcct;
} catch (DmlException e) {
// Process exception here
}
Update Statement 33

The update DML operation modifies one or more existing sObject records, such
as individual accounts or contacts invoice statements, in your organization’s
data.
• Update is analogous to the UPDATE statement
• Syntax
update sObject
update sObject[]
Update Statement 34

The following example inserts an account named 'Acme’:

Account a = new Account(Name='Acme2');


insert(a);
Account myAcct = [ SELECT Id, Name, BillingCity
FROM Account
WHERE Id =:a.Id];
myAcct.BillingCity = 'San Francisco';
try {
update myAcct;
} catch (DmlException e) {
// Process exception here
}
Upsert Statement 35

• The upsert DML operation creates new records and updates sObject records
within a single statement, using a specified field to determine the presence of
existing objects, or the ID field if no field is specified.
• Syntax
upsert sObject[opt_field]
upsert sObject[opt_field]

• This example performs an upsert of a list of accounts.


List<Account> acctList = new List<Account>();
// Fill the accounts list with some accounts
try {
upsert acctList;
} catch (DmlException e) {}
Delete Statement 36

• The delete DML operation deletes one or more existing sObject records, such
as individual accounts or contacts, from your organization’s data. Delete is
analogous to the delete() statement in the SOAP API.
• Syntax
delete sObject | ID
delete sObject[] | ID[]

• The following example deletes all accounts that are named 'DotCom’:
Account[] doomedAccts = [SELECT Id, Name
FROM Account
WHERE Name = 'DotCom'];
try {
delete doomedAccts;
} catch (DmlException e) {}
Undelete Statement 37

• The undelete DML operation restores one or more existing sObject records,
such as individual accounts or contacts, from your organization’s Recycle Bin.
• Undelete is analogous to the UNDELETE statement in SQL.
• Syntax
undelete sObject | ID
undelete sObject[] | ID[]
• The following example undeletes an account named 'Trump'. The ALL ROWS
keyword queries all rows for both top level and aggregate relationships,
including deleted records and archived activities.
Account[] savedAccts =[SELECT Id, Name FROM Account
WHERE Name = 'Trump’ ALL ROWS];
try {
undelete savedAccts;
} catch (DmlException e) {}
Merge Statement 38

• The merge statement merges up to three records of the same sObject type
into one of the records, deleting the others, and re-parenting any related
records.
• Syntax
• merge sObject sObject | ID
• merge sObject sObject[] | ID[]
• The following example merges two accounts named 'Acme Inc.' and 'Acme'
into a single record:
Merge Statement 39

• The following example merges two accounts named 'Acme Inc.' and 'Acme'
into a single record:
List<Account> ls = new List<Account>{new Account(name='Acme Inc.’),
new Account(name='Acme')};
insert ls;
Account masterAcct = [SELECT Id, Name FROM Account
WHERE Name ='Acme Inc.' LIMIT 1];
Account mergeAcct = [SELECT Id, Name FROM Account
WHERE Name = 'Acme' LIMIT 1];
try {
merge masterAcct mergeAcct;
} catch (DmlException e) {
// Process exception here
}
Programmatic Model 2
*In addition to all the Trailhead assignments
SOQL
1. Write a SOQL query to retrieve/print all active Users. Prepare a Map having User Id as key and User record as value. (Hint:
Use Map<Id, User>)
2. Create a multi-select pick list on the Account object called ‘Enrollment Year’ with values - 2010, 2011, 2012, 2013, 2014,
2015, and 2016. Get all account records where in selected
'Enrollment Year' is: a. 2010
b. 2013 and 2014
3. Write a SOQL query to find all Account records where 'Billing State' is not 'Maharashtra' and 'Kerala'. Order the results by
Billing State in descending order with null values at the end. Display the first 10,000 records only. Note: Do not use AND
operator.
4. Write a SOQL query to display 100 opportunity records with amounts greater than 10,000 orders by created date. Skip the
first 50 records and include records from recycle bin.
Aggregate Functions
1. Write a SOQL query to retrieve a sum of all closed Opportunity amounts for the current fiscal year. Store this information in
a map with key as year and value as the sum of the amount. Iterate this map to display statistics.
2. Find a total number of distinct Lead records on basis of ‘Lead Source’ having greater than 10 leads. Print this information.
3. Write a SOQL query to find the total number of Lead records by status by Lead Source. Store this information on the map and
display the same. (Hint: Map<String, Map<String, Integer>>)
Relationship Queries
Create a custom object 'A', 'B' and 'C'. Establish 'Master Detail' relationship between them such that
‘C’ is junction object.
1. Write a SOQL query on Contact to retrieve all active contacts belonging to 'media' Industry. Also display
the name of the account to which it is associated to.
2. Write SOQL query on 'C'(created above) to retrieve all records of 'C' with name 'John' along with parent
details.
3. Write a SOQL query on Account and find all associated contact records of the Account which
contains the word 'John'. Print all Account and Contact records retrieved above.
4. Write a SOQL query to find all Account records which have at least an opportunity record which is
'Closed Won'.
5. Write a SOQL query on 'A' and retrieve all parents with all their child records where in child name is
'John'.
SOSL
1. Find the word 'test' in all name fields returning Contact, Account, Lead and User.
2. Describe SOSL limits.
DML Operations
1. Create a custom object called as 'Logs'. Create a long text area field called as 'Error'. Create 100 Lead
records using DML operations having a unique name. For all records which were not inserted into Lead
object, insert a record in Log object along with the reason why a record was not inserted. Also, execute
assignment rules to auto allocate Lead records to correct owner.
2. Delete all inactive Account records created in last 90 days.
3. Create a custom text field on the Asset object named 'Line Item Id' and mark it as an external id.
Salesforce.com Training
Developer Module
Triggers in Salesforce
Created By – Nanostuffs Team
Overview 2
Overview 3

• An Apex code that executes before or after certain operations are performed in
database.
• Type of Events
• Before
• Validation
• Data updatein same record
• Creating dependentdata
• After
• Creating related records
• Outbound Calls
• Notification
Overview 4

• Events:
• insert
• update
• delete
• merge
• upsert
• undelete
Exercise on Before & After Triggers 5

• Allow users to modify Opportunity record only if record is not Closed.


• Create Order record from Opportunity when its marked as Closed Won.
• Assign a Task to follow-up for Opportunity Owner with Primary Contact as soon as new
record is created.
• Send a Status update to Primary Contact as soon as Opportunities move from one stage
to another.
• Create Total Amount field in Account record to capture Opportunity’sAmount (Roll-up)
Order Of execution andTrigger 6

System/user Validation Rule


Apex (before) triggers
Custom Validation Rules
Record saved to DB (notcommitted)
Record reloaded fromDB
Apex (after) triggers
Assignment Rules
Auto-Response Rules
Workflow Rules
Escalation Rules
RollupSummary Formulas updated
Database Commit
Post-commit logic (Sending emails)
Points to Remember 7

• Trigger on object A can in turn invoke another Trigger on Operation B. All such
operations are considered as a single unit of work.
“Beware of Governor Limits”
• upsert triggers fire both before and after insert or before and after update
triggers as appropriate.
• merge triggers fire both before and after delete triggers for the losing records
and before update triggers for the winning record only.
• Triggers that execute after a record has been undeleted only work with specific
objects.(Account,Contact,Custom Objects etc)
• Field history is not recorded until the end of a trigger. If you query field history in
a trigger, you will not see any history for the current transaction.
Syntax 8

• trigger triggerName on ObjectName (trigger_events)


{
//code_block
• }
• Where trigger events can be a comma-separated list of one or more of the following
events:
• before insert
• before update
• before delete
• after insert
• after update
• after delete
• after undelete
Variables & Methods 9

• isExecuting
• isInsert
• isUpdate
• isDelete
• isBefore
• isAfter
• isUndelete
• New (only for Insert & Update)
• newMap (only for before update, after insert, and after update triggers)
• Old (only for update and delete triggers)
• oldMap (only for update and delete triggers)
• Size
Exercise 10

• Create an Opportunity record with POC Email ID.

• Maintain Total Amount field in Account of Closed Won Opportunities.

• Based on Email id sent with Opportunity record, find Contact under parent Account
record and associate it with Opportunity as Contact Role and Mark it Primary contact.
Exceptions Handling inTrigger 11

• addError() - Triggers can be used to prevent DML operations from occurring by calling
the addError() method on a record or field.

• allOrNone parameter of a Database DML method

• Try-Catch Block
Best Practices 12

• Bulkify Code
• Use Collections (List, Set & Map) to avoid repetitive queries
• Batches

• Never write code in Trigger.


• Do it in Handler class and call it from Trigger

• Try to avoid creating multiple triggers for same events.

• Avoid recursive logic


DebuggingApex 13

• Apex supports a number of facilities for debugging and testing code.


• These include:
• Detailed debug logs and the System Log console.
• Support for the creation and execution of unit tests.
• User-friendly error messages and stack traces for uncaught exceptions.
• Execution governors to prevent runaway scripts from monopolizing shared resources
profiles of performance information.
DebuggingApex 14

• Click System Log | Log Category | Apex Code


• Click System Log | Log Level | Debug
DebuggingApex 15
DebuggingApex: 16

Click Setup > Click New >


• Administration • Choose User > Save
Click View to see
Setup > Monitoring > the logs
Debug Logs
Testing & CodeCoverage 17

• To facilitate the development of robust, error-free code, Apex supports the creation and
execution of unit tests.
• Unit tests are class methods that verify whether a particular piece of code is working
properly or not.
• Unit test methods take no arguments, commit no data to the database, send no emails,
and are flagged with the testMethod keyword in the method definition.
• Syntax of TestMethod:
public class myClass
{
static testMethod voidmyTest()
{
code_block
}
}
Best Practices for Writing Unit Tests 18

• Cover as many lines of code as possible.


• In the case of conditional logic (including ternary operators), execute each branch of
code logic.
• Make calls to methods using both valid and invalid inputs.
• Complete successfully without throwing any exceptions, unless those errors are
expected and caught in a try…catch block.
• Always handle all exceptions that are caught, instead of merely catching the general
exception.
Best Practices for Writing Unit Tests 19

• Use System.assert methods to prove that code behaves properly.


• Use the runAs method to test your application in different user contexts.
• Use the isTest annotation. Classes defined with the isTest annotation do not count
against your organization limit of 1 MB for all Apex scripts.
• Exercise bulk trigger functionality — use at least 20 records in your tests.
• Use the ORDER BY keywords to ensure that the records are returned in the expected
order.
Automated Unit Testing in Apex
Types of Testing 2

▪ Unit Testing
▪ User Acceptance Testing
▪ Regression Testing
▪ End to End Testing
Introduction to Apex Unit Testing 3

Code Coverage
Test Case @isTest
Requirement
Preparation Annotation
for Deployment

Adding asserts Test Method Creating Test


to your tests Syntax Data

Running tests
Test Class Example 4
Best Practices for Test Classes

▪ Cover all test cases


▪ 1 Test method = 1 Test case
▪ Naming convention for test methods
▪ Test method without asserts is not testmethod
▪ Avoid SeeAllData=true
▪ Aim higher: 100%
Exercise 20

Which keyword specifies


that the declared
method contains unit
test code?

Which annotation
specifies that the
declared class contains
unit test code?
– Programmatic Model 3
*In addition to all Trailhead questions
1. Write a Trigger on Account which will create the clone record.
2. Contact Duplicate Check Trigger
Create a new Trigger on Contact that will check for duplicates before allowing a new record
into the database. Validate against the email address and phone number fields. An error be thrown with the error
message –“A Contact with the same email address or phone number already exists in system.” Should be bulk safe in
nature and must be capable of handling at least 200 records at a time.
3. Address Did Not Verify – AVS:
a. Create SalesHeader c object having lookup to Account & Contact & add necessary fields
b. Create EFT_Transaction_Status c object with the necessary fields and add look up
to SalesHeader c
c. Create assignment record type on Case
d. On Insert of a EFT_Transaction_Status c,
If EFT_Transaction_Status c.Method_Name c = “Credit Card Address Verify” & EFT_Transaction_Status
c.Transaction_Status c= “Declined” &
SalesHeader c.Status c = “Open”
e. Create a Case with this mapping:
Value
SalesHeader c.Bill_to_Customer c
Case Field SalesHeader c.Bill_to_Customer c
Account Contact Assignment
Record Type "Internal"
Origin Owner AVS Queue
Address Did Not Verify
Reason Priority High
Status Subject New
Type Account.Name + " " + Case.Type
Open_Sales_Order c Address Did Not Verify
Transaction_Status c SalesHeader c.Id
EFT_Transaction_Status c.Transaction_Status
Sales_Order_Number c c SalesHeader c.Name
Order_Date c EFT_Transaction_Status c.Transaction_Date c
Salesforce.com Training
Developer Module
Salesforce Apex Code Best Practices
Created By – Nanostuffs Team
Agenda 2

• Best practices for Apex Coding

• Best practices for Test Class Writing General Best


Practices

• Custom Salesforce Email Template Best Practices Must Have

AdministrativeTools

• Understanding Governor Limits


Best Practices: Apex 3

Bulkify your Code & Helper Methods. Use SOSL over SOQL where possible – it’smuch
faster.

Avoid SOQL Queries inside FOR Loops. Using


No DML statements inside loops.

Collections, Streamlining Queries, and


Efficient For Loops. Use @future Appropriately.

Use of the Limits Apex Methods to Avoid Hitting


Governor Limits. No Async (@future) methods inside loops.

Apex code must provide proper exception


handling. Do not use hardcoded IDs.

When querying large data sets, use a SOQL “for”


loop. Avoid using multiple queries.
Best Practices: Apex 4

• Commenting and Indentation


1. Class Level Commenting
2. Method Level Commenting
Best Practices: Apex 5

• Use 100 character line limit


• Use tab as 4 spaces
• SOQL and SOSL Query format
Best Practices: Trigger

There should only be one trigger for each object.

Avoid complex logic in triggers.

To simplify testing and reuse, triggers should delegate to Apex classes


which contain the actual execution logic.

Bulkify any “helper” classes and/ or methods.


Best Practices: Trigger 7

Triggers should be “bulkified” and be able to process up to 200 records


for each call.

Execute DML statements using collections instead of individual records


per DML statement.

Use Collections in SOQL “WHERE” clauses to retrieve all records back in


single query.

Use a consistent naming convention including the object name (e.g.,


AccountTrigger).
Best Practices: Test Class 8

Use a consistent naming convention including “Test” and the name of the class being tested (e.g.,
Test_AccountTrigger)

Test classes should use the @isTest annotation

Test methods should create all data needed for the method and not rely on data currently in the Org.

Use System. Assert liberally to prove that the code behaves as

expected. Test each branch of conditional logic

Write test methods that both pass and fail for certain conditions and test for boundary conditions.
Best Practices: Test Class 9

Test triggers to process 200 records

• Make sure your code is “bulkified” for 200 records and doesn’t throw the dreaded “Too many
SOQL queries: 21″ exception.

When testing for governor limits, use –

• Test.startTest and Test.stopTest


• The Limit class instead of hard-coding governorlimits.
Use System.runAs() to execute code as a specific user to test for sharing rules (but
not CRUD or FLS permissions).

Execute tests with the Force.com IDE and not the Salesforce.com UI.
Best Practices: Test Class 10

We have seen misleading code coverage results when running


from the Salesforce.com UI

Run the force.com security source scanner to test your org for a
number of security and quality issues
• For example, Cross Site Scripting, Access Control Issues,Frame Spoofing

Use Separate Test Classes.


General Best Practices: Naming Conventions 11

When using camel case, if you are including an acronym in a name, please only capitalize the first letter.

For Examples,Cross Site Scripting, Access Control Issues, Frame Spoofing Page

S should be camel case and begin with a capital letter.

If using a custom controller or a controller extension, the extension name should be <PageName> Controller.

Class names should always be in camel case with the first letter capitalized.

Class variables and Properties should be camel case with the first letter lower cased.

Field Sets should be used to replace any hardcoding of “arbitrary” fields used in Visualforce table views and
pageBlockSection field views.
Custom Salesforce Email
12
Template Best Practices
Add meaningful alt Include HTML
Create template
text to your header heading to breakup
folder text
banner

Manage images easy to read on Add social media


or department icons to the bottom
within your group Use a font that’s
of your template.
(Amazon S3) mobile devices

Create a header Keep your subject Provide a way for


banner (300 pixels) to 50 characters or recipients to
fewer unsubscribe.
General Best Practices: Field Sets& Try Catch Blocks 13

Appropriate use of Try Catch


Usage of Field Sets
Blocks
• Field Sets should be used to replace any • Try Catch blocks should be written to handle
hardcoding of “arbitrary” fields used in very specific exception types and handle
Visualforce table views and pageBlockSection those appropriately.
field views. • The error MUST be reported to either the
user or emailed to a SystemAdmin.
• For VF pages, all error messagesshould be
shown under
• <apex:message> tag
• For Triggers, “Do Nothing Catch All” try catch
blocks are discouraged, however catching and
re-wording of specific exceptions is
acceptable.
General Best Practices 14

Public Static Class


Folder Structure
Variables
• Public static variables should be • Project specific static resources should
declared as “public static final have thefollowing subfolders:
<variable>”. • CSS
• These variables should be named in all • Image
Uppercase with underscores “_”
• Script
separating words.
Debugging in Salesforce 15

• What is Debug Logs?


• Debug level and categories
• Log line

• Debug logs can contain information about:


• Database changes
• HTTP callouts
• Apex errors
• Resources used by Apex
• Automated workflow processes
Debugging in Salesforce 16
Day 14 – Best Practices
ABC Containers require the ability to automatically associate a Contact created in their Salesforce Instance with
the respective Account based on the email domain specified in the primary email address of the Contact. The
association should happen real time as soon as a Contact record is created within the system.
TODO
• Ensure all the discussed implementation best practices are followed.
• Develop the necessary piece of Apex code to implement a solution for the given problem statement.
• Develop the necessary Test code to attain the right code coverage (minimum 90% with at least 4 test
cases)
Salesforce.com Training
Developer Module
Visualforce Pages - Part I
Created By – Nanostuffs Team
Agenda 2

• Visualforce – Overview & Architecture

• Model - View - Controller

• Visualforce Markup

• Controllers

• Global Variables
Visualforce 3

Visualforce is a framework that User interfaces can extend the standard


allows developers to build Force.com look and feel or replace it
sophisticated, custom user with a unique style and set of
interface can be hosted natively interactions
on the Force.com platform
Visualforce 4

User Interface
can extend the
Complete standard Visualforce is
framework for Force.com look
Complete available in
enabling any kind and feel, or
framework for Group,
of interface replace it with a
building and Professional,
design and complete unique
deploying any Enterprise,
interaction to be style and set of
kind of user Unlimited and
built and interactions,
experience Developer
delivered entirely allowing the Editions
on demand power of PaaS to
be extended to
virtually any
requirement
Visualforce 5

CSS Style

Component Tag Standard


HTML

Data Expression
Visualforce: MVC Pattern 6

Model View Controller

Standard
Objects Pages

Controllers

Custom
Components
Objects

Schema and User Interface User Interface


Data and Data actions and
representation Business Logic
Visualforce: Architecture 7
Visualforce: Pages 8

• Design definition of the application's user interface.

• Composed of HTML, Page tags and data expression.

• Ability to reference CSS, AJAX, Flex and other web technologies.

• Supports standard query strings for parameters, referenced by apex/page URLsyntax.

• Composed on the server, not the client.

• Data is placed on the page using Expressions.

• Expressions are filled-in on the server.


Visualforce: Components 9

• Create standard UI elements, such as detail areas and related lists, with a single tag.

• Built in data-binding.

• Special UI elements such as tabs and iterators.

• Built-in AJAX functionality to support incremental refresh.

• Multiple components are available for developing a Visualforce page.

• Accesses through <apex:tagname> syntax

• The detail attribute adds a complete page layout.

• The subject attribute identifies the record to display.


Where can you use Visualforce? 10

• Override standard buttons, such as the New button for accounts.

• Override tab overview pages, such as the Accounts tab home page.

• Define custom tabs.

• Embed components in detail page layouts.


Create Hello World Page 11

• Open Developer Console

• Click File -> New -> Visualforce Page

• Enter Page Name: ‘HelloWorld’

• Click Preview
Displaying Field Values on a Page 12

• The {!account.name} expression makes a call to the getAccount() method in the


standard Account controller to return the record ID of the account currently in context. It
then uses dot notation to access the name field for that record.

• You can get name of specific account using:

https://na3.salesforce.com/apex/HelloWorld?id=001D000000HRgU6
Custom Controllers 13

• Used to write custom logic for the page

• Override the functionality of the standard controllers by writing custom functions

• Cannot be used along with a standard controller


Controller extensions 14

• Add additional behavior/functionality to the standard/custom controllers

• We can add number of controller extensions to a salesforce page

• Can be used along with the standard/custom controllers


Global Variables 15

• You can use global variables to reference general information about the current user and
your organization on a Visualforce Page

• All global variables must be included in expression syntax.


For Example: {! $User.Name }
Global Variables 16
Visualforce Pages I
*In addition to all the Trailhead questions
Managing Attachments
1. We need to develop a two-step wizard to update account information and manage attachments
related to the account.
2. Take a custom button and place it on the detail page for the account.
3. On click of the button, a Visualforce page should be opened.
4. The page should display the account details in a page block and display the related attachments
in the page block below it in tabular format.
5. The table showing the attachments should have a link to delete an attachment record.
6. The page consists of an Edit button and on click of which a two-step wizard should be opened.
7. On the first step of the wizard, the details of the account should be shown in edit mode and with the
click of the next button, the page should navigate to the second step.
8. On the second step, a browse button should be shown so that the user can browse for a file and upload
it as an attachment.
9. The account details entered by the user and the uploaded file using the browse button should be
saved with the click of the save button in the second step.
Salesforce.com Training
Developer Module
Visualforce Pages - Part II
Created By – Nanostuffs Team
Agenda 2

• AJAX

• JavaScript - Remoting

• Static Resources

• Standard VF Tags

• Unit Testing

• Quiz
AJAX 3

• Applying AJAX Behavior to Events on Any Component.

• Implementing Partial Page Updates with Command Links and Buttons.

➢ Update specific portion of a page rather than a reload of the entire page

➢ Implement a partial page update using: reRender attribute

➢ When a user clicks the button or link, only the identified component by ID and all of its
child components are refreshed
AJAX 4

Problem:
• User clicks the name of a contact in the list
• To view the details for that contact
• The entire page is getting refreshed as a result of this action
AJAX 5

Solution:
• Use reRender attribute
• Provide ID to desired portion of the page that should be reRendered
Javascript Remoting 6

• Used to invoke controller actions via JavaScript

• Called in an asynchronous execution context

• Faster than using normal visualforce actions


Static Resources 7

• Static resources allow you to upload content that you can reference in a Visualforce page,
including archives (such as .zip and .jar files), images, stylesheets, JavaScript, and other files.

• You can reference a static resource by name in page markup by using the $Resource global
variable instead of hard-coding document IDs.

• A single static resource can be up to 5 MB in size, and an organization can have up to250
MB of static resources, total.
Static Resources 8

• Create Static Resource:


➢ Open Developer Console
➢ Click File -> New -> Static Resource

• Use Static Resource:

➢ Single File:
<apex:image url="{!$Resource.TestImage}" width="50" height="50" />

➢ Zip File:
<apex:image url="{!URLFOR($Resource.TestZip, 'images/Bluehills.jpg')}" width="50"
height="50" />
VisualForce Tags: commandButton 9

• Displays a button in standard salesforce style

• Can be used to call controller methods using “action” attribute


VisualForce Tags: Links 10

• Salesforce provides two default types of links:


➢ commandLink
➢ outputLink
• Used to display links in standard salesforce style
• commandLink can be used to call controller methods using “action” tag
• outputLink does not support “action” tag
Iterating over a list of data 11

• Salesforce allows iterating over a data set using standard components

• <apex:repeat> tag is used to iterate

• The components inside <apex:repeat> and </apex:repeat> are repeated

• Can be used on lists, sets or the keys of a map


Unit Testing 12

• To Unit test Visualforce page functionality, we need write test classes for custom
controllers and
• extensions.

• Set the visualforce as current page in test


methods using
• Test.setCurrentPage(PageReference
currentPage)

• Create object of custom controller or extension

• Get/Set URL parameters (if required)

• Write test methods from user perspective to test different scenarios.


Quiz 13
Part 1 – Theory
1. What is AJAX, how can you use it on your page?
2. How does Salesforce provide AJAX in visualforce pages?
3. What are the different “action” tags in Salesforce?
4. List out the uses of the different attributes of the <apex:actionFunction> tag
5. What are the apex “command” tags that Salesforce provides?
6. What is the difference between a commanLink and an outputLink?
7. How can you refresh the contents of a VF page without causing it to reload?
8. What are the apex “reRender” and the apex “actionRegion” tags?
9. How can you implement JavaScript in your VF pages?
10.What is the method in JavaScript to perform the following:
a. Open a link in a new tab/window
b. Close the current tab
c. Reload the page
11.How can you call a controller method from JavaScript?
12.Can you pass parameters to the controller while invoking an actionFunction?
13.What is VF remoting? How is it different from normal apex actions?
14.What are the advantages/disadvantages of VF remoting over normal apex actions?
15.What are static resources? How can you create them in Salesforce?
16.What all files can be supported by static resources?
Part 2 – Practical
1. The accounts manager should be able to view a list of all the accounts present in my organization. Develop a VF page
for the same. The columns that should be present on the page are:
a. Account Name
b. Email address
c. Phone number
d. Website
e. A button named “Manage Contacts”
On clicking the account name, he/she should be redirected to the account detail page. Also on clicking the
website of the account, he/she should be taken to the same in a new tab. Generate a table for the same. Use
standard Visualforce table components.
2. The account manager now wants the function to search for a particular account from the account list page. Add a
textbox to the top of the VF page that will take the account name. Add a button as well that will perform the search on
the accounts and display the results accordingly. The count of the accounts should also be updated. The search should
also be performed on pressing the enter button on the keyboard. If nothing has been entered in the textbox, a
message should be displayed stating that “Input at least 3 characters to perform search”. The results of the search
should be displayed without refreshing the page. Also add a link to clear the search results.
3. Implement “alphabetical search” on the accounts page. The page should contain a strip of all the alphabets on
the top. On clicking the alphabet, the account list should be refreshed without reloading the actual page. Hint:
Use apex actionFunction for the same.
4. Create a new link to delete the account. On clicking the link, the account should be deleted using VisualForce
Remoting. On successful deletion, an alert should be displayed on the page stating “The account has been
deleted”. Figure out the advantages/disadvantages of using VF remoting in this scenario.
5. Store the script of the VF remoting in a JS file inside a zip file. Upload that file to the static
resources and include the same in your page.
6. Get an image for the header of your page. Add that image to the static resources. Add the header to the page
Hint: Use the download link
7. Write the test classes for all the custom controllers and extensions that you have used in the application. Follow
best practices for the same. Create a utility class for generating the test
data. Make sure you cover all the test scenarios. Focus on covering the scenarios rather than code coverage. Use
meaningful asserts.
Salesforce.com Training
Developer Module
Application Settings
Created By – Nanostuffs Team
Agenda 2

• Custom Labels
• Translation Workbench
• Custom Settings
• Custom Metadata Type
Custom Code Development 3

Enable developers
Allow developer to deploy
Custom labels to create
application metadata with
are custom Custom text multilingual
records which avoids using
text values values can applications by
be migration tool or post
that can be automatically
translated installation script for
accessed from presenting
into any creating records within the
Apex classes information in a
language organization.
or Visualfo user's native
Salesforce Example: UserName and
rce pages. language.
Supports Password details
Example: help
messages
Custom Labels in Apex & Visualforce 4

Syntax for accessing Labels in Apex


class

• System.Label.Label_name

Syntax for accessing Labels in


Visualforce Page

• $Label global variable


5
Points to Remember

You can create up to 5,000 custom labels for


your organization, and they can be up to 1,000
characters in length.
Translation Workbench 6

The Translation Workbench lets you -

• Specify languages you want to translate.


• Assign translators to languages.
• Create translations for customizations you’vemade to
your Salesforce organization.
• Override labels and translations from managed packages.

Everything from custom picklist values to custom fields can be translated


so your global users can use all of Salesforcein their language.
Translation Workbench 7

To enable the Translation Workbench.

• Setup
• Click Translation Workbench
• Translation Settings
• On the Welcome page
• Click Enable
User Permission needed to enable
Translation Workbench.

•“Manage Translation” permission


Setup & Manage Translation Workbench 8
Standard Account Page 9
After Applying Translation Workbench 10
Custom Settings 11

Custom settings
are similar to
Custom datacan
custom objects Enable creation
and association of then be used by
and enable
formula fields,
application custom data foran
validation
developers to organization, rules, Apex, and
create custom profile, or specific
sets of data. user. the SOAP API.
Accessing Custom Settings Data 13
Custom Metadata Types 14

Can Custom
Custom It enables The
provide data then
metadata feature of Records
Record-level can be
are similar association themselves
used by
to custom protection
of custom Apex. Can’t are
objects and of
data for yet perform Metadata,
more configuration
an CUD on APEX
advanced
and custom
version of organization, Tests can
custom field-level metadata
profile, types in see them
setting. control over
or specific Apex even with
who can
user. “SeeAllDat
edit values.
a=False”
Custom Metadata Type 17

• Custom metadata types support the followingcustom


field types:

● Checkbox
● Metadata Relationship
● Date
● Date and Time
● Email
● Number
● Percent
● Phone
● Picklist
● Text
● Text Area
● URL
● Currency
18
Quiz 19

• What are different types of Custom Settings?

• How to access Custom Labels in ApexClass?

• User permission needed to enable/ manage


Translation Workbench
• Advantages of Custom Metadata Type over Custom

Settings
Application Settings
*In addition to all the questions in the following Trailhead –
Custom Metadata Types Basics
Programmatic Development with Custom Metadata Types
Assignment 1: Country-City Dependent Picklist
1. Create a list custom setting named “Country”. Create four records of this custom setting:
a. Name = India
b. Name = France
c. Name = Italy
d. Name = USA
2. Create another list custom setting named “City”. Add a field “Country” of data type text on
this custom setting. Create the following records of this custom setting:
a. Name = New Delhi, Country = India
b. Name = Mumbai, Country = India
c. Name = Pune, Country = India
d. Name = Kolkata, Country = India
e. Name = Ney York, Country = USA
f. Name = Miami, Country = USA
g. Name = Washington DC, Country = USA
h. Name = Paris, Country = France
i. Name = Lyon, Country = France
j. Name = Milan, Country = Italy
k. Name = Rome, Country = Italy
3. Create a Visual Force page. This page should display two picklists, one for Country and
another for City. Initially, the city picklist should not display any value; instead, it should be dependent upon the Country picklist. So when the user selects a
particular country then the City picklist should load all the cities corresponding to the selected country.
Assignment 2: Student Registration Form
1. Create a custom object “Student”. Create the following fields on this object:
a. Student Name – Text
b. Roll Number – Number
c. Gender – Picklist – (Male, Female)
d. Course Applying for – Picklist – (B.E., B. Arch, M.C.A, B.C.A)
e. H.S.C % - Percentage
f. S.S.C % - Percentage
g. Country – Text
h. State – Text
i. City – Text
2. Create a VF Page. This page should display a student registration form. And a submit button.
3. On click of submit button student record should get created with details provided by the user, and a success
message (“Your admission application has been submitted successfully”) should be displayed on the page.
4. At the top of this Visualforce page there should be a picklist to select language. The Language picklist
should have 3 options: English, French, and Spanish.
5. The page should display content in the language selected by the user.
Assignment 3: Hierarchical Custom Setting
Create a Hierarchical custom setting “TriggerSetting”. Create fields for all triggers developed in your
system. This custom setting should be used to enable/disable any trigger from your org.

Assignment 4: Custom Label Translation


Create a VF page to translate the Custom Label text as per the language selected on the
page.

Assignment 5: Validation Rule Setting


Create custom setting “ValidationSetting”. This custom setting should be used to
activate/deactivate any Validation Rule from your org.
Salesforce.com Training
Developer Module
Asynchronous Apex
Created By – Nanostuffs Team
Agenda 2

● Batch Apex

● Scheduled Apex

● Future Methods

● Queueable Apex
Batch Apex 3

● What is Batch Apex?


● Where can we use batch apex?
● Using Batch Apex

Start Execute Finish

• Collect the • Performs the • Used to execute


records or objects actual processing post-processing
to be passed for for each chunk or operations and is
processing “batch” of data called once after
passed to the all batches are
method processed.
Batch Apex 4

● Batch Apex Syntax


○ Database.Batchable interface
○ Database.QueryLocator
○ Iterable
○ Database.Stateful
● Invoking a Batch Class
● Apex limits when using batch
Batch Apex 5

● Sample Batch Apex class:


Scheduled Apex 6

● What is Scheduler?
● Where can we use Scheduler?
● Using Scheduler
○ Schedulable interface
○ Execute method
Scheduled Apex 7

● Sample Scheduled Apexclass:


Scheduled Apex 8

● System.schedule Method
● Cron Expression
● Apex Scheduler Limits
Future Methods 9

● What is Future Methods?


● Where can we use Future Methods?
● Using Future Methods
○ @future annotation
○ use for callout
Queueable Apex 10

● What is Queueable Apex?


● Using Queueable Apex
○ Queueable interface
● Difference between Queueable Apex and Future method
● Queueable Apex Limits
References 11

● https://developer.salesforce.com/docs/atlas.en-
us.apexcode.meta/apexcode/apex_invoking_future_methods.htm
● https://developer.salesforce.com/docs/atlas.en-
us.apexcode.meta/apexcode/apex_queueing_jobs.htm
● https://developer.salesforce.com/docs/atlas.en-
us.apexcode.meta/apexcode/apex_scheduler.htm
● https://developer.salesforce.com/docs/atlas.en-
us.apexcode.meta/apexcode/apex_batch.htm
Asynchronous Apex
*In addition to all the Trailhead assignments
Removal of duplicate Leads
1. During the Campaigning, it might happen that a representative creates duplicate leads in an org.
2. So admin wants to build a process that will run every 3 hours/day & remove the duplicate leads from the org.
3. The criteria to find the duplicate records should be configurable.
Ex. If there are two leads in a system with the same Email address, then keep the first lead entry & remove all the
other leads.
4. So the field like Email, Name which will be deciding the uniqueness should be configurable.

Generic Record Creation Engine


1. The third-party system will create events in a system to create any SObject's records
2. There will be a field that will hold the JSON of the record & the object name. JSON: {
Name: XYZ Solutions
}
Object Name: Account
3. So create a process that will execute per minute & process the Event's records creating the respective SObject.
4. JSON deserialize method
https://developer.salesforce.com/docs/atlas.enus.apexcode.meta/apexcode/apex_class_Sys
tem_Json.htm#apex_System_Json_deserialize
Salesforce.com Training
Developer Module
Web Services in Salesforce
using REST
Created By – Nanostuffs Team
Agenda 2

What are Web Services?

Types of Web Services

Some Basic Terminologies Creating Apex

REST Web Services

Performing HTTP Callouts Writing

Unit Tests
What are Web Services? 3

• Applications used to share information over the web


• Provides access from your system to external applications
• Follows pre-defined protocols (SOAP/REST/HTTP)
• Implemented in a Client-Server Fashion
Types of Web Services 4

• RESTful Web Services


• SOAP Web Services

Parameter REST Web Services SOAP Web Services

Full Form Representational State Transfer Simple Object Access Protocol

Specification REST is an Architectural Style SOAP is a Protocol

Data TransferFormat Data can be transferred in JSON, XML,Plain


Data can be transferred only in XML format
Text and more formats

Bandwidth Utilization Lightweight More as compared to REST

Additional Files None Requires WSDL file to be consumed


Some Basic Terminologies 5

Term Meaning

REST Representational StateTransfer, a REST Web Service

SOAP Simple Object Access Protocol, a SOAP WebService

WSDL Web Service Definition Language file, contains information about SOAP webservice

Endpoint URL and the path to be called in order to invoke the web service

Request Information sent to the system

Response Information received from the system

Publisher/Provider System that creates a new web service and makes it available to the public

Consumer System that performs a call to the publisher and expects a response

Callout Communication message sent from the consumer to the publisher


Creating Apex REST Web Services 6

• Make Apex classes callable through the web as REST or SOAP web services
• Need to specify the path where web services are called
• Requires authentication
• Uses annotations to indicate the type of actions

Annotation Usage

@RestResource Used at the class level to expose the class as a RESTweb service

@HttpGet Used at the method level for functions that read or receive records

@HttpPost Used at the method level for functions that create new records

@HttpDelete Used at the method level for functions that deleterecords

@HttpPut Used at the method level for functions that upsert records

@HttpPatch Used at the method level for functions that update fields in existing records
Code Samples 7

How to test the WebService?

Go to Workbench
https://workbench.developerforce.com

Log In and Navigate to Utilities > REST


Explorer

Select method as GET

Enter the URLas


“/services/apexrest/Cases/<case_id>

Click on Executebutton
Code Samples 8

How to test the WebService?

Log In to workbench and


navigate to RESTexplorer

Select method as POST Enter

the URL as
“/services/apexrest/Cases”

Add JSON body for details of Case


to be created

Click on Execute button


Consuming from outside Salesforce 9

Authentication Callout
• Instance URL • Session Id
• Connected App • Refresh Token
• URL Mapping • Headers
• Named
Credential • Request
Create Obtaining
Endpoint Access
Unit Testing Apex REST 10

Web Services
Performing HTTP Callouts 11
Writing Unit Tests 12

• Apex Test Methods do not support callouts

• Test methods that perform callouts fail with an exception

• While testing a “mock” needs to be specified to the testing framework

• HttpCalloutMock method can be used to write a mock response

• Using the “Test.setMock()” method, a mock response can be specified


Writing Unit Tests – Code Sample 13
Web Services using REST
*In addition to all the Trailhead assignments
Lead Manipulator Service
1. Create an Apex REST Service that will help external systems to manipulate Leads within Salesforce
2. The REST Service should provide the following capabilities
a. Create a new Lead in Salesforce basis the First Name, Last Name, Email, and Phone values.
b. The service should return a response specifying the following

Sr. No. Parameter Name Value

1 isSuccess True only if Lead creation is successful


2 lead Record Id of the newly created Lead. Blank in
case of lead creation failure
3 status “Success” if lead creation is successful. Should
return an error message in case of failure
3. Delete the Lead record in Salesforce basis the FirstName, LastName, Email and Phone exact match combination.
The above attributes will be posted to the REST Service as input params and the service should return a response
specifying the following:
Sr. No. Parameter Name Value
1 isSuccess True only if Lead creation is successful
Full Name of the deleted Lead. Blank in case of
2 Lead lead deletion failure
3 Status “Success” if lead creation is successful. Should
return an error message in case of failure

4. Update the Email and Phone fields of Lead record in Salesforce basis the First Name and Last Name exact match combination.
The following attributes will be posted to the REST Service - First Name, Last Name, New Email and New Phone. The service
should return a response specifying the following:
Sr. No. Parameter Name Value
1 isSuccess True only if Lead creation is successful
Full Name of the deleted Lead. Blank in case of
2 Lead lead deletion failure
3 Status “Success” if lead creation is successful. Should
return an error message in case of failure

5. Write appropriate test code for the REST Service Apex code to achieve 100% test code coverage (atleast 90%).
Salesforce.com Training
Developer Module
Web Services in Salesforce
using SOAP
Created By – Nanostuffs Team
Introduction to SOAP 2

• SOAP (Simple • Web service • WSDL is an XML • You’ll probably use


Object Access callouts to SOAP format for describing SOAP mostlywhen
Protocol) is a web services use network services as a integrating with
protocol XML, and typically set of endpoints legacy applications
specification for require a WSDL operating on or for transactions
exchanging document for code messages containing that require a
structured generation. either document- formal exchange
information (such oriented or format or stateful
as XML) securely procedure- oriented operations.
over internet. information.
PUBLISHER 3

Apex Class WSDL Unit Test Considerations

• Publishing
the apex • Generating a • Test Classes • Limitations
class using WSDL from for the and Know
WEBSERVICE apex class webservice how's of
keyword methods exposing a
webservice
Apex Class 4
Generating a WSDL 5

Select "Generate
Setup Develop Apex <Your Class WSDL"
Classes
Name> button
Unit Testing and TestClass 6
Considerations 7

1. Invoking a custom webservice method always uses system context.


2. Sharing rules (record-level access) are enforced only when declaring a class with the wit h sharing keyword.
3. All classes that contain methods defined with the webservice keyword must be declared as global.
4. Define any method that uses the webservice keyword as s t a t i c .
SUBSCRIBER 8

WSDL WSDLToApex Consumption Unit Test


Generation

• Obtain a WSDL • Generate an


apex class • Consume the • Unit test the
of the external service and
from WSDL generated
webservice
class in your implement
class and save • Use the
apex code the test class.
it on you local salesforce
system WSDLToApex
Generator
WSDL File 9

1. Get a WSDL file of the service which you want to consume.


2. Store a WSDL file locally on your machine.
WSDLToApex Generation 10

"Generate Apex
Apex Classes
Setup Develop from
WSDL"button

Generate Apex Provide the Apex Choose the WSDL


Parse WSDL
Code Class Name file from your
local machine
Consumption 11
Unit test and Test Class 12
Web Services using SOAP
*In addition to all the Trailhead assignments
Lead Manipulator Service
1. Create an Apex SOAP Service that will help external systems to manipulate Leads within Salesforce
2. The SOAP Service should provide the following capabilities
a. Create a new Lead in Salesforce basis the First Name, Last Name, Email, and Phone values.
b. The service should return a response specifying the following
Sr. No. Parameter Name Value
1 isSuccess True only if Lead creation is successful
2 lead Record Id of the newly created Lead. Blank in
case of lead creation failure

3 status “Success” if lead creation is successful. Should


return an error message in case of failure

3. Delete the Lead record in Salesforce basis the FirstName, LastName, Email and Phone exact match
combination. The above attributes will be posted to the SOAP Service as input params and the service should
return a response specifying the following:
Sr. No. Parameter Name Value
1 isSuccess True only if Lead creation is successful
2 lead Full Name of the deleted Lead. Blank in case of
lead deletion failure
3 status “Success” if lead creation is successful. Should
return an error message in case of failure
4. Update the Email and Phone fields of Lead record in Salesforce basis the First Name and Last
Name exact match combination. The following attributes will be posted to the SOAP Service
- First Name, Last Name, New Email and New Phone. The service should return a response
specifying the following:

Sr. No. Parameter Name Value


1 isSuccess True only if Lead creation is successful
2 lead Record Id of the updated Lead. Blank in case of
lead updatefailure

3 status “Success” if lead creation is successful. Should


return an error message in case of failure

5. Write appropriate test code for the SOAP Service Apex code to achieve 100% test code coverage (atleast 90%).
Salesforce.com Training
Developer Module
Introduction to Lightning
Components
Created By – Nanostuffs Team
Lightning Design System 2

• Salesforce’s native CSS framework like BootStrap, Material Design or


Foundation etc.
• Collection of Design Pattern, Components & guidelines for creating
unified UI on Salesforce
• Adaptive designing using Grid System & UI Component
Lightning Component Framework 3

• Modern UI Framework ○ Dynamic Single Page Web Apps


• Mobile and Desktop Friendly
• Built on Aura
• Apps are built from components
• Units of functionality, small and large
• Encapsulation and Decoupling
• The Lightning Component framework is a UI framework for
developing web apps for mobile and desktop devices.
• It's a modern framework for building single-page applications
with dynamic, responsive user interfaces for Lightning Platform
apps.
• It uses JavaScript on the client side and Apex on the server
side.
Visualforce Vs Lightning 4

Visualforce Lightning Components


• Stateful Server • Stateful Client, Stateless server
• State is maintained across the calls. • Instant updates after client side
changes
• Only necessary data retrieved from
server
• Page Centric • Event- Driven Communication
• Heavy on server calls • Decoupled and light-weight

• Lots of generated code and markup • Mobile Friendly


• In lightning components, a component is a bundle of code.
• The bundle contains all the resources related to a component like
javascript controller, helper, renderer, css styles etc.
• A basic lightning component contains the design of a page in html
with some lightning tags.
Lightning Component Framework 5

• Lightning Component Bundle


• Component File - *.cmp
• Javascript Controller - *.js
• Javascript Helper - *.js
• CSS Styles - *.css
• Documentation - *.auradoc
• Renderer - *.js
• SVG File - *.svg
Thinking Component… 6

• Understand the requirement


• Visualize the required output
• Divide the app into smaller
components
• You are ready to go...
Lightning Component Basics 7

• Define attribute
• <aura:attribute
• required : By default set to false
• default : The default Value to be set
• name : The attribute Name
• type : The type of attribute either Primitive Datatype, Objects, Collections, Apex Class
etc.
• ></aura:attribute>
• Ex.
<aura:attribute name=“message”
type=“String”
default=“You look nice today!”>
</aura:attribute>
Lightning Component Basics 8

• Value Providers / Aura Expressions


• {!v.AttributeName}
• <ui:input*> - * could be Text,Date,Radio,Phone,Number, Email, Date,
DateTime, RichText, Secret, Select, etc.
Ex.
<ui:inputDate aura:id="dateField" label="Birthday" value="2014-01-30"
displayDatePicker="true"/>
• <ui:output*> -* could be Text, Date, Radio, Phone, Number, Email,
Date, DateTime, RichText, Secret, Select, etc.
Ex.
<ui:outputDate value="{!v.myDate}"/>
Lightning Component Basics 9

• aura:if
Ex.
<aura:if isTrue="{!v.truthy}">
True
<aura:set attribute="else">
False
</aura:set>
</aura:if>
Lightning Component Basics 10

• <ltng:require styles=”style1, style2...style n”


scripts=”script1,script2….,script n” />
Ex.
<ltng:require styles="/resource/SLDS105/assets/styles/salesforce-lightning-
design-system-ltng.css" scripts= " "/>
• <aura:iteration items=”{!v.Accounts}” var=”acc”/>
Ex.
<aura:iteration items="1,2,3,4,5" var="item">
<meter value="{!item / 5}"/><br/>
</aura:iteration>
Where can you use Lightning Components? 11

• Lightning Applications
• Lightning RecordPages
• Lightning HomePages
• Communities
Standard Lightning Component references 12

• lightning:datatable
A lightning-datatable component displays tabular data where each column can be
displayed based on the data type. For example, an email address is displayed as a hyperlink
with the mailto: URL scheme by specifying the email type. The default type is text
• lightning:spinner
A lightning-spinner displays an animated spinner image to indicate that a feature is loading.
This component can be used when retrieving data or anytime an operation doesn't
immediately complete. The variant attribute changes the appearance of the spinner.
• lightning:icon

A lightning:icon is a visual element that provides context and enhances


usability. Icons can be used inside the body of another component or on their own.
Specify the icon with the iconName attribute
• ltng:require

ltng:require enables you to load external CSS and JavaScript libraries after you upload
them as static resources. Use the styles attribute to specify a resource name and CSS
file. Use the scripts attribute to specify a resource name and JavaScript file.
Salesforce.com Training
Developer Module
Lightning Components Server
Side Communication
Created By – Nanostuffs Team
Agenda 2

• Invoking Apex from Lightning Component


• Standard Lightning Component
• Lightning Out
• LDS
• Debugging in Lightning Component
• Best Practices
Lightning Component Framework(Client-Server)

3
Invoking Apex from Lightning Component 4

• @AuraEnabled
• Static methods
• Callback function
• Passing parameters to the server method
• enqueueAction
Lightning Out 5

Lightning Out is a feature that extends Lightning Apps and acts as a bridge to
surface Lightning Components in any remote web container.

• Take your Lightning Component outside theSalesforce

• Lightning Component inside Visualforce Pages


• Pulls your Lightning components app over a secure connection and inserts it into
the DOM of the pageit’s running on.
• Lightning Out is added to external apps in the form of a
JavaScript library you include in the page on the origin server
Lightning dependency app 6

A Lightning dependency app must do the following.


• Set access control to GLOBAL.
• Extend from either ltng:outApp or ltng:outAppUnstyled.
• List as a dependency every component that is referenced in a callto
$Lightning.createComponent().

Lightning out dependency app is used for when you want to display
your lightning component into VisualForce Page in Salesforce. By Clicking the Checkbox it
enables you to display the lightning component into the VisualForce page
Lightning Out Dependencies 7

• Describe the component dependencies of a Lightning components app


• Dependency Apps structure:
Lightning Component in VF Page 8

• There are three steps to add Aura components to a Visualforce page.


• Include <apex:includeLightning/> in Visualforce Component.
• Create and reference a Lightning app that declares your component
dependencies.
• Write a JavaScript function that creates the componenton the page using
$Lightning.createComponent().
Lightning Out Markup
9
Lightning Out requires some simple markup on the page, and is activated using two straightforward
JavaScript functions. The markup and JavaScript functions in the Lightning Out library are the only
things specific to Lightning Out.

Creating a Componenton a Page


Lightning Data Service 10

Lightning Data Service is a centralized data caching framework which


is used to load, save, create and delete a record without server-side
apex code. It supports the sharing rules and field-level security as well.

• Use to load, create, edit, or delete a record without writing Apex code
• Serves as the data layer for Lightning.
• Identifies and eliminates requests that involve the same record data, sendsa
single shared data request that updates all relevantcomponents.
• Can be used to work on offline mode and syncing the data once user is online.
LDS force:recordData 11

A force:recordData component defines the parameters for accessing, modifying, or creating


a record using Lightning Data Service. You have granular control on how you want to display
or render the data in your custom component.

• Loads record on client side.


• Set below attributes in force:RecordData
• recordId: specifies the record to load.
• Mode: can be set to either EDIT orVIEW
• layoutType: specifies the layout (FULL or COMPACT) used to display the record,
which determines what fields are included.
• Fields: specifies which fields in the record toquery.
• targetRecord: The provided record.
• targetFields: A simplified view of the fields in targetRecord
• targetError: Will be set to the localized error message if the record can't be provided.
Parameters 12

• Loads record on client side.


• Set below attributes in force:RecordData
• recordId: specifies the record to load.
• Mode: can be set to either EDIT orVIEW
• layoutType: specifies the layout (FULL or COMPACT) used to display the record, which
determines what fields are included.
• Fields: specifies which fields in the record toquery.
• targetRecord: The provided record.
• targetFields: A simplified view of the fields in targetRecord
• targetError: Will be set to the localized error message if the record can't be
provided.
force:recordData Methods 13

• getNewRecord():
Loads an empty record template intov.targetRecord
• Includes any predefined default values for the object and record type
• reloadRecord():
• Performs the same load function as on init
• Performs server trip only if required
• saveRecord():
• Saves the current record
• deleteRecord():
• Deletes the current record
Debugging In Lightning Component 14

• https://developer.salesforce.com/blogs/developer-relations/2015/03/debugging-
lightning-components.html
• Server-side Debugging of Lightning Components
• Using the JavaScript Debugger in Lightning Components
• Client-side Logging in Lightning Components.
15
Best Practices

• Data retrieval
• Data caching
• Lightning DataService
• Component instantiation
• Conditional rendering
• Events
• Lists (aura:iteration)
Salesforce.com Training
Developer Module
Communicating between
Lightning Components
Created By – Nanostuffs Team
Agenda 2

• Inter-component Communication
• Communication Patterns
• Event Life-cycle
• Locker Service
Inter-component Communication 3

• Why communicate?

o Encapsulation of UI and related logic in single component


o Isolated components for security
o Interaction is necessary

• Event driven programming

• Actions and Events


Action and Event Example 4

1. Button click action


2. Action invokes click handler
3. Controller function invokes
helper function
4. Helper function calls an Apex
controller method
5. Apex method executed
6. A JavaScript callback function is
invoked
7. Callback function is executed and
component is re rendered
8. User sees updated component
Communication Patterns 5

• Hierarchical

o Parent to Child
o Child to Parent
Communication Patterns (continued...)
• Non-hierarchical

o Between Components
Attributes and Methods 7

Attributes are the most commonly used element to pass data down the component hierarchy.

parentComponent.cmp
<aura:component>
<aura:attribute name="parentAttribute" type="String"/>
<c:childComponent childAttribute="{!v.parentAttribute}"/>
</aura:component>

childComponent.cmp
<aura:component>
<aura:attribute name="childAttribute" type="String"/>
</aura:component>
Attributes and Methods (continued… 1) 8

Using attribute change event/handler

childComponent.cmp
<aura:component>
<aura:attribute name="childAttribute" type="String"/>
<aura:handler name="change"
value="{!v.childAttribute}"
action="{!c.onChildAttributeChange}"/>
</aura:component>
Attributes and Methods (continued… 1) 9

childComponentController.js
({
onChildAttributeChange : function (component, event, helper) {
console.log("Old value: " + event.getParam("oldValue"));
console.log("Current value: " + event.getParam("value"));
}
})
Attributes and Methods (continued… 2) 10

A better parent to child communication approach: Methods

It is like an API for parent component to ask child component to perform an action.

How it works:

1. Method is defined in the child component using <aura:method> tag with a name and required parameters.

1. Parent component has a reference to child component in it’s controller.

1. Using this reference to child Component, parent component can directly call the named method defined in #1
Attributes and Methods (continued… 3) 11

Exposing a method from child component

childComponent.cmp
<aura:component>
<aura:method name="myMethod" action="{!c.executeMyMethod}">
<aura:attribute name="param1" type="String"/>
<aura:attribute name="param2" type="String"/>
</aura:method>
</aura:component>
Attributes and Methods (continued… 3) 12

childComponentController.js
({
executeMyMethod : function (component, event, helper) {
var params = event.getParam('arguments');
console.log('Param 1: '+ params.param1);
console.log('Param 2: '+ params.param2);
}
})
Attributes and Methods (continued… 4) 13

Calling child component method from parent component

parentComponent.cmp
<aura:component>
<aura:attribute name="parentAttribute1" type="String" default="A"/>
<aura:attribute name="parentAttribute2" type="String" default="B"/>

<c:childComponent aura:id="child"/>

<lightning:button label="Call child method" onclick="{!c.onCallChildMethod}" />


</aura:component>
Attributes and Methods (continued… 5) 14

parentComponentController.js
({
onCallChildMethod : function(component, event, helper) {
var attribute1 = component.get('v.parentAttribute1');
var attribute2 = component.get('v.parentAttribute2');
var childComponent = component.find('child');
childComponent.myMethod(attribute1, attribute2);
}
})
Returning values from aura:method 15

• aura:method executes synchronously

• But,

o The function defined on aura:method can be either

1.Synchronous
or
2. Asynchronous

o Synchronous method can return immediately after execution finishes

o Asynchronous method may return before the result of server side action is received
Returning values from 16

aura:method (continued..)
What if parent component needs to know the response that the asynchronous aura:method received?

We are going to use… Callback function

▪ aura:method will have a parameter with type=”Function”

▪ Parent needs to send a function to callback later

presentation.goAhead(comeToThisSlideLater);
Events in Lightning Framework 17

How events work?

• Framework uses event-driven programming


• Custom events are written by developers fired from Javascript controller actions
• Events contain attributes to pass data
• Different that browser events as framework is notified about these events

Types of events

• Component event
• Application event
• System event
Component Event 18

• Similar to DOM events


• Propagate event up in the component hierarchy
• Child to Parent communication

Propagation

• Both capture and bubble phase is supported


• Similar to DOM
• Interact with event and control behaviour of subsequent handlers
Application Event 19

• Use publish-subscribe model


• Broadcast event to all components
• Communication between non-hierarchical components

Propagation

• Default Phase
• Event handlers are invoked in a non-deterministic order from the
root node through its subtree.
Event Best Practices 20

• Use Component Events whenever possible

• Separate Low-Level Events from Business Logic Events

• Dynamic action based on component state

• Use event dispatcher to listen and relay events

• Don't Fire an Event in a Renderer


System Events 21

• Standard events used by framework


• Components can listen to them for custom logic
• Example:

o aura:valueChange
o aura:valueInit
o aura:valueRender

Events provided by framework

Example:

o force:createRecord
o force:showToast

Handled by one.app container


Event lifecycle 22

• When an event is fired, the framework does a lot of work in the backend.

• Steps in the lifecycle:

1. Detect the fired event


2. Determine event type
3. Execute each handler
4. Re-render component (...if attributes are changed)
Locker Service 23

• Security architecture for Lightning Components


• Based on component namespace
• A component can only traverse the DOM and access elements created by a component in the same namespace
• Secure Wrappers
o Hidden global objects or secure versions of those objects
o Eg: SecureWindow for window
Salesforce.com Training
Developer Module
Visualforce and Lightning
Component Best Practices
Created By – Nanostuffs Team
Agenda 2

Why to Follow Best Practices?

How to Write Good VF Pages

Tips for Writing JavaScript and CSS in Pages Best

Practices for Lightning Components

Tips for Migrating from VF Pages to Lightning

Conclusion
How to Write Good VF Pages 4

• Use Salesforce provided components

• Use formulas instead of variables

• Make correct use of static and transient variables to optimize the view-state

• Design consistent user experience

• Limit the number of extensions for one page to minimum

• Query only the data to be displayed

• Implement lazy loading when loading large amounts of data


Tips for Writing JavaScript and CSS in Pages 5

• Always remember, JavaScript is CasE sENsiTivE

• Put JavaScript, CSS and Image files inside Static Resource

• Follow folder structures while including JavaScript, CSS and Images inside Static Resource

• Include only the functions you need inside your JavaScript files

• Combine multiple JavaScript and CSS files to one JavaScript and CSS file to reduce HTTP requests

• Use JavaScript and CSS Minifiers to reduce the size of your files

• Place your <script> and <style> tags to include files at the bottom of the page (wherever possible)

• Set showHeaders and standardStylesheets attributes of the <apex:page> tag to false when not using standard
Salesforce styles
Best Practices for Lightning Components 6

• Follow Naming Convention for all components

• Do not leave commented code/tags in any file of the component bundle

• Distinguish all the tags inside the component with a logical separation

• Try minimizing the server requests

• Group multiple attribute declaration together that serve a common purpose

• Use helper functions to write reusable code

• Prefer the use of components with lightning namespace over using ui namespace

• Use plain JavaScript instead of jQuery


Tips for Migrating from VF Pages to Lightning 7

• Create backups of existing working code before making any changes

• Focus on using wrapper classes than multiple attributes/parameters

• Study the functionality of VF thoroughly before designing the component structure

• Carefully divide the business logic between Aura methods and JavaScript functions

• Be sure of data model before starting the development

• Design component hierarchy efficiently to provide similar UX between VF and Lightning

• Avoid chaining of controller actions


Conclusion 8

You might also like