Developer PDF
Developer PDF
Language basics
Debugging
Topics 3
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?
Apex scripts can be initiated by Web service requests and from triggers
on objects.
How does Apex work? 5
• 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
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
public clas
public interface Purcha
Double discount();
}
}
Extending virtual Classes 14
/ / 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
Abstract method does not have method body. It just has method
signature
Interfaces & Extending Classes 16
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
Wrapper Class
Data Types 19
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{
/* 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
A literal expression.
• For example:
1+1
• 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
• For example:
• Integer i = 1;
• Account a = new Account();
• Account[] accts = [select id from account];
Loops 30
Do-While
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
instanceof
transient
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
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.
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:
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
Exception handling
sObject variables are initialized to null, but can be assigned a valid object
reference with the newoperator.
• For example:
• Account a = newAccount();
• For example:
• Account a = new Account(name = 'Acme', billingcity = 'San Francisco');
Accessing sObject Fields 7
• For example:
DML operations 8
• 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 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.
Apex provides exception handling using try catch blocks similar toJava
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
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
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.
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
• 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:
Similar to SQL, SOQL also makes use of the SELECT statement to fetch data.
Let us explore the following SOQLsyntax:
You can add multiple field expressions to a condition expression by using logical
operators:
[ SELECT Id
FROM Event
WHERE What.Type IN ('Account', 'Opportunity')]
The Comparison Operators 6
• When querying the records using the date field or the date and time field in the
SOQL statement, the date formats should be followed.
• When querying the records using the date field in the SOQL statement, the
date literals can be used.
The INCLUDES and EXCLUDES operators are used to filter the multiselect
picklist field.
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.
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.
• 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:
• Aggregate functions allow you to roll up and summarize your data in a query.
• e.g. AVG(), COUNT(), MIN(), MAX(), SUM(), and more.
• 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
• These relationships are traversed by specifying the parent using dot notation
in the query.
• 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.
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:
• Anti Join: Returns rows from first table where no matches are found in the
second table. Use NOT IN operator.
• Example:
• 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:
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.
• The OFFSET clause along with LIMIT is useful in retrieving a subset of the
records or implementing pagination.
• You can search text, email, and phone fields multiple objects—including
custom objects—that you have access to in a single query.
• 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
• 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 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 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]
• 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
• 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
• 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
• 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.
• Try-Catch Block
Best Practices 12
• Bulkify Code
• Use Collections (List, Set & Map) to avoid repetitive queries
• Batches
• 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
▪ 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
Running tests
Test Class Example 4
Best Practices for Test Classes
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
AdministrativeTools
Bulkify your Code & Helper Methods. Use SOSL over SOQL where possible – it’smuch
faster.
Use a consistent naming convention including “Test” and the name of the class being tested (e.g.,
Test_AccountTrigger)
Test methods should create all data needed for the method and not rely on data currently in the Org.
Write test methods that both pass and fail for certain conditions and test for boundary conditions.
Best Practices: Test Class 9
• Make sure your code is “bulkified” for 200 records and doesn’t throw the dreaded “Too many
SOQL queries: 21″ exception.
Execute tests with the Force.com IDE and not the Salesforce.com UI.
Best Practices: Test Class 10
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
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
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
• Visualforce Markup
• Controllers
• Global Variables
Visualforce 3
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
Data Expression
Visualforce: MVC Pattern 6
Standard
Objects Pages
Controllers
Custom
Components
Objects
• Create standard UI elements, such as detail areas and related lists, with a single tag.
• Built in data-binding.
• Override tab overview pages, such as the Accounts tab home page.
• Click Preview
Displaying Field Values on a Page 12
https://na3.salesforce.com/apex/HelloWorld?id=001D000000HRgU6
Custom Controllers 13
• You can use global variables to reference general information about the current user and
your organization on a Visualforce Page
• AJAX
• JavaScript - Remoting
• Static Resources
• Standard VF Tags
• Unit Testing
• Quiz
AJAX 3
➢ Update specific portion of a page rather than a reload of the entire page
➢ 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
• 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
➢ 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
• To Unit test Visualforce page functionality, we need write test classes for custom
controllers and
• extensions.
• 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
• System.Label.Label_name
• Setup
• Click Translation Workbench
• Translation Settings
• On the Welcome page
• Click Enable
User Permission needed to enable
Translation Workbench.
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
● Checkbox
● Metadata Relationship
● Date
● Date and Time
● Email
● Number
● Percent
● Phone
● Picklist
● Text
● Text Area
● URL
● Currency
18
Quiz 19
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.
● Batch Apex
● Scheduled Apex
● Future Methods
● Queueable Apex
Batch Apex 3
● What is Scheduler?
● Where can we use Scheduler?
● Using Scheduler
○ Schedulable interface
○ Execute method
Scheduled Apex 7
● System.schedule Method
● Cron Expression
● Apex Scheduler Limits
Future Methods 9
● 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.
Unit Tests
What are Web Services? 3
Term Meaning
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
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
• 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
@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
Go to Workbench
https://workbench.developerforce.com
Click on Executebutton
Code Samples 8
the URL as
“/services/apexrest/Cases”
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
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
• 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
"Generate Apex
Apex Classes
Setup Develop from
WSDL"button
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:
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
• 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
• aura:if
Ex.
<aura:if isTrue="{!v.truthy}">
True
<aura:set attribute="else">
False
</aura:set>
</aura:if>
Lightning Component Basics 10
• 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
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
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.
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
• 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
• 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?
• 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
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
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. Using this reference to child Component, parent component can directly call the named method defined in #1
Attributes and Methods (continued… 3) 11
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
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"/>
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
• But,
1.Synchronous
or
2. Asynchronous
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?
presentation.goAhead(comeToThisSlideLater);
Events in Lightning Framework 17
Types of events
• Component event
• Application event
• System event
Component Event 18
Propagation
Propagation
• Default Phase
• Event handlers are invoked in a non-deterministic order from the
root node through its subtree.
Event Best Practices 20
o aura:valueChange
o aura:valueInit
o aura:valueRender
Example:
o force:createRecord
o force:showToast
• When an event is fired, the framework does a lot of work in the backend.
Conclusion
How to Write Good VF Pages 4
• Make correct use of static and transient variables to optimize the view-state
• 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
• Distinguish all the tags inside the component with a logical separation
• Prefer the use of components with lightning namespace over using ui namespace
• Carefully divide the business logic between Aura methods and JavaScript functions