0% found this document useful (0 votes)
15 views25 pages

SFC Unit-Iii Notes

This document provides an overview of Apex programming basics, including its features, such as being tightly integrated with Salesforce, object-oriented, and strongly typed. It covers key concepts like SOQL for querying data, DML operations for data manipulation, and the use of classes and methods for building custom logic. Additionally, it explains relationship queries and dynamic SOQL, emphasizing the importance of handling exceptions and governor limits in Apex.

Uploaded by

lathasanthiya279
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)
15 views25 pages

SFC Unit-Iii Notes

This document provides an overview of Apex programming basics, including its features, such as being tightly integrated with Salesforce, object-oriented, and strongly typed. It covers key concepts like SOQL for querying data, DML operations for data manipulation, and the use of classes and methods for building custom logic. Additionally, it explains relationship queries and dynamic SOQL, emphasizing the importance of handling exceptions and governor limits in Apex.

Uploaded by

lathasanthiya279
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/ 25

Unit-III : APEX PROGRAMMING BASICS

Programming with Apex: Introduction to Apex - Statements & Collections - Introduction


to Apex Classes. SOQL: Syntax, SOQL in Apex, Dynamic SOQL. Query using
relationships: Relationship name, child-to-parent relationship – parent-to-child
relationship.DML essentials: DML operations with Apex - Transaction Controls - DML
errors.

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.

Key Features of Apex:

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.

Object-Oriented: Apex is an object-oriented language, which means it supports


principles such as classes, objects, inheritance, and polymorphism. This facilitates
building modular and maintainable 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.

Governor Limits: Salesforce imposes governor limits on the amount of resources


(such as CPU time, memory, and database queries) that Apex code can consume
within a single transaction. This prevents runaway code from negatively impacting
the performance of the Salesforce platform.

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.

Exception Handling: Apex includes exception handling mechanisms for managing


errors and exceptions that might occur during code execution. This helps ensure that
your code remains stable and robust.

Visualforce Integration: Apex can be used in conjunction with Visualforce, a


framework for building custom user interfaces in Salesforce. You can use Apex to
add dynamic behavior to Visualforce pages.

Integration: Apex supports integration with external systems through APIs and web
services, allowing you to connect Salesforce with other applications and services.

Testing Framework: Salesforce provides a comprehensive testing framework for


Apex code, enabling developers to write unit tests to ensure code quality and
reliability.
Security and Sharing: Apex adheres to Salesforce's security and sharing model,
ensuring that your custom code respects the access controls and permissions defined
in the platform.

Statements & Collections:

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:

Variable Declaration and Assignment:

Integer num = 10; // Declaration and assignment

String message; // Declaration

message = 'Hello, World!'; // Assignment

Conditional Statements:

if, else if, else:

if (num > 0) {

// Code to execute if num is positive

else if (num < 0) {

// Code to execute if num is negative

else {

// Code to execute if num is zero

}
Looping Statements:

for loop:

for (Integer i = 0; i < 5; i++) {

// Code to execute in each iteration

while loop:

Integer i = 0; while (i < 5) {

// Code to execute in each iteration i++;

Switch Statement:

Integer day = 3;

switch (day) {

case 1:

// Code for Monday

break;

case 2:

// Code for Tuesday

break;

// ...

default:

// Code for other days

}
Exception Handling:

try, catch, finally:

try {

// Code that might throw an exception

catch (Exception e) {

// Code to handle the exception

finally {

// Code that executes regardless of whether an exception occurred

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.

List<Integer> numbers = new List<Integer>();

numbers.add(10);

numbers.add(20);

Integer secondNumber = numbers[1]; // Accessing element at index 1

Sets: Sets are collections that store unique values. Duplicate values are automatically
removed.

Set<String> colors = new Set<String>();

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.

Map<String, Integer> scores = new Map<String, Integer>();

scores.put('Alice',85);

scores.put('Bob',92);

Integer aliceScore = scores.get('Alice'); // Retrieving value using key

Collections Iteration:

List<String> fruits = new List<String>{'apple', 'banana', 'orange'};

for (String fruit : fruits) {

System.debug(fruit); // Output: apple, banana, orange

These are just a few examples of statements and collections in Apex.

Introduction to Apex Classes


In Apex, a class is a blueprint for creating objects that represent real-world
entities or concepts. It encapsulates data and behavior together, allowing you to
define the structure and functionality of your custom objects. Apex classes serve as
the foundation for building custom business logic, data manipulation, and
application functionality within the Salesforce platform. Here's an introduction to

Apex classes:

Creating a Class: To create an Apex class, you define its structure using the
following syntax:

public class MyClass {

// Variables (properties) and methods (functions) go here

// Constructor
public MyClass() {

// Initialization code

// Methods

public void myMethod() {

// Code for the method

Access Modifiers:

public: The class is accessible throughout the Salesforce org.

private: The class is only accessible within the same class.

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.

Constructor: A constructor is a special method that is called when an object of the


class is created. It is used to initialize the object's properties and perform any
necessary setup.

Example: Here's a basic example of an Apex class:

public class Car {

public String make;

public String model;


public Integer year;

public Car(String make, String model, Integer year) {

this.make = make;

this.model = model;

this.year = year;

public void startEngine() {

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:

Car myCar = new Car('Toyota', 'Camry', 2023);

myCar.startEngine(); // Output: Engine started for 2023 Toyota Camry

Inheritance: Apex supports inheritance, allowing you to create subclasses that


inherit properties and methods from a parent class. This promotes code reusability
and modularity.

Apex Class Visibility: Apex classes can be visible in various contexts:

Global: Accessible everywhere, even outside the package.

Public: Accessible within the package.

Private: Accessible only within the class.

Use Cases: Apex classes are used for various purposes, including:

➢ Implementing custom business logic.


➢ Manipulating and processing data.
➢ Interacting with the Salesforce database (using SOQL and DML).
➢ Creating custom web services.
➢ Defining triggers to automate processes.
➢ Building custom controllers for Visualforce pages.
➢ Integrating with external systems using APIs.

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.

Key features of SOQL:

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.

Relationships: SOQL supports traversing relationships between objects. You can


query fields from related objects using dot notation.

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.

Example SOQL Queries:

Here are some examples of SOQL queries to illustrate its syntax:


Basic Query:

SELECT Name, Industry FROM Account

Filtering with WHERE:

SELECT Name, StageName FROM Opportunity WHERE CloseDate > TODAY

Sorting with ORDER BY:

SELECT LastName, FirstName FROM Contact ORDER BY LastName ASC

Relationships:

SELECT Name, Account.Name FROM Contact

Aggregate Function:

SELECT Account.Name, COUNT(Id) FROM Contact GROUP BY Account.Name

Subquery:

SELECT Name, (SELECT LastName FROM Contacts) FROM Account

Using SOQL in Apex:

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:

List<Account> accounts = [SELECT Name, Industry FROM Account WHERE


Industry = 'Technology'];

for (Account acc : accounts) {

System.debug('Account Name: ' + acc.Name + ', Industry: ' + acc.Industry);

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

[USING SCOPE filterScope]

[WHERE conditionExpression]

[WITH [DATA CATEGORY] filteringExpression]

[GROUP BY {fieldGroupByList |

ROLLUP (fieldSubtotalGroupByList) |

CUBE (fieldSubtotalGroupByList) |

GROUPING SETS ((fieldSubtotalGroupByList), ...) }]

[HAVING havingConditionExpression]

[ORDER BY fieldOrderByList {ASC | DESC} [NULLS {FIRST | LAST}] ]


[LIMIT numberOfRowsToReturn]

[OFFSET numberOfRowsToSkip]

[FOR {VIEW | REFERENCE}]

Here's an explanation of each part of the SOQL syntax:

SELECT: Specifies the fields you want to retrieve from the object.

TYPEOF: Allows you to perform polymorphic queries.

FROM: Specifies the object you're querying (e.g., Account, Contact).

USING SCOPE: Limits the query to a specific user or group.

WHERE: Defines the conditions for filtering the records.

WITH DATA CATEGORY: Enables filtering based on data categories.

GROUP BY: Groups the results by specified fields.

ROLLUP: Provides subtotals for grouped fields.


CUBE: Provides multiple levels of subtotals.

GROUPING SETS: Defines a list of grouping expressions.

HAVING: Filters groups created by the GROUP BY clause.

ORDER BY: Specifies the sorting order for the results.

LIMIT: Limits the number of records returned.

OFFSET: Skips a specified number of records.

FOR: Specifies the query context (VIEW or REFERENCE).

Example SOQL Queries:

Here are some examples of SOQL queries with explanations:

Basic Query:

SELECT Name, Industry FROM Account

Retrieves the Name and Industry fields from the Account object.

Filtering with WHERE:

SELECT Name, Amount FROM Opportunity WHERE CloseDate > TODAY

Retrieves the Name and Amount fields from the Opportunity object where the
CloseDate is greater than today.

Sorting with ORDER BY:

SELECT LastName, FirstName FROM Contact ORDER BY LastName ASC

Retrieves the LastName and FirstName fields from the Contact object, ordered by
LastName in ascending order.

Relationship Query:

SELECT Name, Account.Name FROM Contact

Retrieves the Name field from the Contact object and the Name field from the related
Account object.
Aggregates with GROUP BY and HAVING:

SELECT Account.Name, COUNT(Id) FROM Contact GROUP BY Account.Name


HAVING COUNT(Id) > 5

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.

In Salesforce, SOQL is used to query data from Salesforce objects (like


records in a database) such as standard objects (e.g., Account, Contact) or custom
objects that you define. Dynamic SOQL allows you to build these queries
dynamically using variables and expressions, which gives you flexibility in
constructing queries based on runtime conditions.

Here's an example in Apex, Salesforce's programming language, of how you


might use dynamic SOQL:

String objectName = 'Account'; String fieldName = 'Name';

String searchValue = 'Acme'; String query = 'SELECT Id, ' + fieldName + ' FROM
' + objectName + ' WHERE ' + fieldName + ' LIKE \'%' + searchValue + '%\'';
List<SObject> records = Database.query(query);

In this example, the objectName, fieldName, and searchValue variables are


used to construct a dynamic query that searches for records in the specified object
where the specified field matches the search value. The query is then executed using
the Database.query() method.

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.

Dynamic SOQL is commonly used in scenarios where the query structure


needs to change based on user interactions, custom filters, or complex search criteria
that can't be easily achieved with static queries.

Query using relationships:

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.

To be able to traverse these relationships for standard objects, a relationship name is


given to each relationship. The form of
the name is different, depending on the direction of the relationship:
child-to-parent relationship:
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. For
example, the Contact child object has a
child-to-parent relationship to the Account object, so the value of relationship Name
in Contact is Account. These
relationships are traversed by specifying the parent using dot notation in the query,
for example:
In the child to parent relationship, we can query on contact and retrieves the values
from account that is associated.
Contact c = [Select First Name, Last Name, Account.Name, Account.Industry
from contact where id = ‘XXXXXXXX’];
System.debug(‘Account Name: ‘ + c.Account.Name);
System.debug(‘Industry: ‘ + c.Account.Industry);
Parent-to-child relationship:
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. For example, Account has child relationships to
Assets, Cases, and Contacts among other objects, and has a relationship Name for
each, Assets, Cases, and Contacts. These relationships can be traversed only in the
SELECT clause, using a nested SOQL query. For example:
In the parent -to-child relation, we can query on the parent object and we will get
details about child record.
Account a = [Select Name, (Select Contact.FirstName, Contact.LastName from
Account.Contacts) from account where id = ‘XXXX’];
System.debug(‘Name:’+ a.name );
DML operations with Apex

In this blog we are going to learn about DML(Data Manipulation Language)


operations in Salesforce. Following types of DML statements are available in
salesforce.

insert : Use this statement to create the records of sObject.

update : Use this statement to update the existing records of sObject.

upsert: Use this statement to create the new record or update the existing records on
the basis of Id or external field.

delete : Use this statement to delete the existing record

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:

//Create new contact by using insert operation

Contact con = new Contact(FirstName = 'Jon',Salutation='Mr.' LastName='Doe',


Phone ='9838783737');

insert con;
2. Update Operation:

1. //Update existing contact by using update operation


2. Contact cont = [SELECT Id FROM Contact WHERE FirstName = 'Jon' Limit 1];
3. cont.Birthdate = Date.parse('12/3/1994');

update cont;
3. Upsert Operation:

//Create or Update contact by using upsert operation


Contact cont = [SELECT Id FROM Contact WHERE FirstName = 'Jon' Limit 1];
cont.Birthdate = Date.parse('11/3/1994');
upsert cont;

4. Delete Operation:

//Delete existing contact by using delete operation


Contact con = new Contact(FirstName = 'Jon',Salutation='Mr.'
LastName='Doe', Phone ='9838783737');
delete con;
5. Undelete Operation:

//Undelete existing contact by using undelete operation


Contact cont = [SELECT Id FROM Contact WHERE FirstName = 'Jon' ALL ROWS];
undelete cont;
6. Merge Operation:

//Merge contact by using merge operation


Contact con = new Contact(FirstName = 'Jon',Salutation='Mr.'
LastName='Doe', Phone ='9838783737');
insert con;
Transaction Controls in DML operations in salesforce
In Salesforce, transaction controls are used to manage and control data
manipulation language (DML) operations, which include creating, updating,
deleting, and undeleting records in the Salesforce database. Transaction controls
help ensure data integrity and allow you to handle errors that may occur during these
operations. Here are some key aspects of transaction controls in Salesforce:

Database.savepoint and Database.rollback: Salesforce allows you to create


savepoints within a transaction using Database.setSavepoint() and then roll back to
that savepoint if an error occurs. This is particularly useful when you want to handle
errors gracefully and avoid committing partial changes to the database. For example:

Savepoint sp = Database.setSavepoint();

try {

// DML operations

catch (Exception e)

Database.rollback(sp);

Database.commit: To commit changes to the database, you use Database.commit().


This is typically used after a series of DML operations when you are sure that there
are no errors, and you want to save the changes permanently.

// 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();

Database.setSavepoint and rollback: As mentioned earlier, you can create


savepoints and roll back to them as needed to handle errors gracefully and maintain
data consistency.

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.

Transaction Isolation: Salesforce uses a multi version concurrency control system,


which means that changes made by one transaction are isolated from changes made
by other transactions until the changes are committed. This ensures data consistency
and prevents conflicts.

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 errors in apex salesforce


In Salesforce Apex, Data Manipulation Language (DML) errors can occur
when you are performing operations like inserting, updating, deleting, or undeleting
records in the database. These errors can happen for various reasons, and it's
essential to handle them gracefully to ensure the robustness of your code. Here are
some common DML errors and how to handle them in Salesforce Apex:

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)

// Handle DML errors System.debug('DML Exception: ' + e.getMessage());

for (Integer i = 0; i < e.getNumDml(); i++)

Database.Error err = e.getDmlMessage(i);

System.debug('DML Operation ' + i + ' caused an error: ' + err.getMessage());

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:

Database.SaveResult[] srList = Database.insert(records, false);

for (Database.SaveResult sr : srList)

if (!sr.isSuccess())

// Handle individual record errors for (Database.Error err : sr.getErrors())

System.debug('Error: ' + err.getMessage());

Limit Exceeded: DML operations are subject to governor limits in Salesforce. If


you exceed these limits, you will encounter LimitException errors. You can catch
and handle these exceptions in your code.

Custom Error Handling: Depending on your application's requirements, you may


want to implement custom error handling logic to respond to specific DML errors.
For example, you could create custom error messages or log errors for later analysis.

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.

You might also like