SFC Unit-Iii Notes
SFC Unit-Iii Notes
Introduction to Apex:
Apex is a programming language developed by Salesforce specifically for
building and customizing applications on the Salesforce platform. It is a strongly-
typed, object-oriented language that enables developers to create complex business
logic, automate processes, and interact with the underlying Salesforce data and
services.
Tightly Integrated with Salesforce: Apex is tightly integrated with the Salesforce
platform, allowing developers to access and manipulate Salesforce data, metadata,
and features directly within their code.
Strongly Typed: Apex is strongly typed, meaning you need to declare the data types
of variables and parameters explicitly. This enhances code reliability and catches
errors at compile time rather than runtime.
Triggers: Triggers are blocks of Apex code that are executed before or after specific
events occur in Salesforce, such as record creation, update, or deletion. Triggers
allow you to automate business processes and enforce data integrity.
Classes and Methods: Apex supports the creation of classes and methods, enabling
developers to encapsulate functionality into reusable components. Classes can have
variables (properties) and methods (functions) just like in other programming
languages.
SOQL and DML: Apex provides Salesforce Object Query Language (SOQL) for
querying and retrieving data from the Salesforce database. It also supports Data
Manipulation Language (DML) statements like insert, update, and delete for
working with records.
Integration: Apex supports integration with external systems through APIs and web
services, allowing you to connect Salesforce with other applications and services.
In Apex programming, statements are the building blocks of code that perform
specific actions or operations. Collections, on the other hand, are data structures used
to store multiple values of the same or different data types. Let's delve into both
concepts in more detail:
Statements in Apex:
Conditional Statements:
if (num > 0) {
else {
}
Looping Statements:
for loop:
while loop:
Switch Statement:
Integer day = 3;
switch (day) {
case 1:
break;
case 2:
break;
// ...
default:
}
Exception Handling:
try {
catch (Exception e) {
finally {
Collections in Apex:
Lists: Lists are ordered collections that can store multiple values of the same data
type. They are similar to arrays in other programming languages.
numbers.add(10);
numbers.add(20);
Sets: Sets are collections that store unique values. Duplicate values are automatically
removed.
colors.add('red');
colors.add('blue');
colors.add('red'); // Ignored since 'red' is already in the set
Maps: Maps store key-value pairs, allowing you to associate values with unique
keys.
scores.put('Alice',85);
scores.put('Bob',92);
Collections Iteration:
Apex classes:
Creating a Class: To create an Apex class, you define its structure using the
following syntax:
// Constructor
public MyClass() {
// Initialization code
// Methods
Access Modifiers:
protected: The class is accessible within the same class and subclasses.
Variables (Properties): Variables within a class are known as properties. They can
store data and be accessed by methods within the class. You can specify access
modifiers for properties as well.
Methods (Functions): Methods define the behavior of a class. They can perform
operations, manipulate data, and interact with other classes or objects. Methods can
have parameters and return values.
this.make = make;
this.model = model;
this.year = year;
System.debug('Engine started for ' + year + ' ' + make + ' ' + model);
Using the Class: You can create instances of the class and use its methods and
properties like this:
Use Cases: Apex classes are used for various purposes, including:
SOQL
SOQL (Salesforce Object Query Language) is a query language used to
retrieve records from the Salesforce database. It is specifically designed for querying
and manipulating data stored in Salesforce objects (also known as tables in database
terminology). SOQL is similar to SQL (Structured Query Language) but is tailored
to the Salesforce data model and provides some unique features for working with
the platform's metadata and relationships.
Retrieving Records: SOQL queries allow you to fetch records from Salesforce
objects. You can specify which fields you want to retrieve and filter records based
on specific conditions.
Filtering and Sorting: SOQL queries support the use of WHERE clauses to filter
records based on field values. You can also use ORDER BY clauses to sort the
results.
Aggregates: SOQL includes aggregate functions like COUNT, SUM, MAX, MIN,
and AVG to perform calculations on grouped records.
Subqueries: You can use subqueries within SOQL queries to retrieve related data
and use it in your main query's conditions or filters.
Querying Custom Objects: SOQL allows you to query both standard Salesforce
objects (e.g., Account, Contact, Opportunity) and custom objects that you create.
Relationships:
Aggregate Function:
Subquery:
In Apex code, you can use SOQL queries to retrieve data and work with it
programmatically. Here's an example of using SOQL in Apex:
SOQL Syntax:
Certainly! Here's the syntax for constructing SOQL (Salesforce Object Query
Language) queries:
SELECT fieldList
[TYPEOF typeOfField whenExpression THEN resultExpression END]
FROM objectName
[WHERE conditionExpression]
[GROUP BY {fieldGroupByList |
ROLLUP (fieldSubtotalGroupByList) |
CUBE (fieldSubtotalGroupByList) |
[HAVING havingConditionExpression]
[OFFSET numberOfRowsToSkip]
SELECT: Specifies the fields you want to retrieve from the object.
Basic Query:
Retrieves the Name and Industry fields from the Account object.
Retrieves the Name and Amount fields from the Opportunity object where the
CloseDate is greater than today.
Retrieves the LastName and FirstName fields from the Contact object, ordered by
LastName in ascending order.
Relationship Query:
Retrieves the Name field from the Contact object and the Name field from the related
Account object.
Aggregates with GROUP BY and HAVING:
Retrieves the Account Name and the count of Contact records per Account, but only
for Accounts with more than 5 Contacts.
Dynamic SOQL:
Dynamic SOQL (Structured Query Language) refers to the ability to create
and execute Salesforce Object Query Language (SOQL) queries dynamically at
runtime, rather than having the query written out as a static string in your code. This
is particularly useful when you need to construct queries based on variable
conditions, user inputs, or other dynamic factors.
String searchValue = 'Acme'; String query = 'SELECT Id, ' + fieldName + ' FROM
' + objectName + ' WHERE ' + fieldName + ' LIKE \'%' + searchValue + '%\'';
List<SObject> records = Database.query(query);
It's important to note that while dynamic SOQL provides flexibility, it can
also introduce potential risks like SQL injection if not handled properly. Always
sanitize and validate user inputs before using them in dynamic queries to prevent
security vulnerabilities.
Using relationship queries, we can retrieve the related objects data using the
SOQL query.
Parent-to-child and child-to-parent relationships exist between many types of
objects, for example, Account is a parent of
Contact.
Below diagram display relationship between Account and Contact.
upsert: Use this statement to create the new record or update the existing records on
the basis of Id or external field.
undelete : Use this statement to restore the records from Organisation recycle bin.
merge : Use this statement to merge the records of same sObject type by deleting
other and re-parenting the related records. You can use upto 3 records to merge.
DML Example
Let’s do some example of above statements. To execute the below mentioned example
GOTO||Developer Console||Debug||Open Execute Anonymous Window.
1. Insert Operation:
insert con;
2. Update Operation:
update cont;
3. Upsert Operation:
4. Delete Operation:
Savepoint sp = Database.setSavepoint();
try {
// DML operations
catch (Exception e)
Database.rollback(sp);
// DML operations
Database.commit();
Database.rollback: If an error occurs during a transaction and you need to roll back
all the changes made since the last savepoint, you can use Database.rollback(). This
effectively cancels the transaction and reverts the database to its state at the last
savepoint.
try
// DML operations
catch (Exception e)
Database.rollback();
Limits and Governor Limits: Salesforce imposes limits on the number of DML
operations that can be performed in a single transaction. It's important to be aware
of these limits to ensure your code does not exceed them. If you do exceed the limits,
you may need to restructure your code to work within the constraints.
Bulk DML Operations: When working with large sets of records, it's often more
efficient to use bulk DML operations like insert, update, upsert, and delete to
minimize the number of DML statements and reduce the risk of hitting governor
limits.
DML Exception Handling: You should always wrap your DML operations in try-
catch blocks to catch and handle any DML exceptions that may occur. The most
common DML exception is DmlException. Here's an example:
try
// DML operations
catch (DmlException e)
The DmlException object provides information about the errors that occurred
during DML operations.
Rollback Transactions: If a DML error occurs and you want to roll back the entire
transaction to maintain data integrity, you can use Database.rollback() as shown in
the previous response.
Partial Success: Salesforce allows partial success for certain DML operations,
which means some records may be successfully processed while others fail. You can
use the Database.upsert and Database.insert methods with the allOrNone parameter
set to false to handle partial success:
if (!sr.isSuccess())
Retry Logic: In some cases, it may be appropriate to implement retry logic for DML
operations that fail due to transient issues (e.g., network problems). You can catch
the exception, wait for a moment, and then attempt the DML operation again.