0% found this document useful (0 votes)
106 views

Trining Final 1 Apex

The document provides an overview of using Apex to work with lists and sObjects. It explains that lists store collections of items and can be initialized with or without elements. Methods like add, get, and size can be used to manipulate list elements. sObjects represent database records and can be created, populated with fields, and inserted into the database using DML statements. The EmailManager class example demonstrates how to send an email using the Messaging class and inspect the results. The challenge answer shows how to create a method that returns a list of formatted strings based on a parameter.

Uploaded by

teja ganesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views

Trining Final 1 Apex

The document provides an overview of using Apex to work with lists and sObjects. It explains that lists store collections of items and can be initialized with or without elements. Methods like add, get, and size can be used to manipulate list elements. sObjects represent database records and can be created, populated with fields, and inserted into the database using DML statements. The EmailManager class example demonstrates how to send an email using the Messaging class and inspect the results. The challenge answer shows how to create a method that returns a list of formatted strings based on a parameter.

Uploaded by

teja ganesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Get Started with Apex

Apex Language Basics

• Apex is a programming language for the Salesforce platform

• Lists are a data structure that store a collection of items of the same data type

• Lists can be created and elements can be added or retrieved using the List class and its methods

• Apex classes can have public or private methods and variables, and can be used to organize and reuse
code

• sObjects are Salesforce objects that represent database records, and can be created and manipulated
using the sObject class

• DML (Data Manipulation Language) statements can be used to manipulate records in the Salesforce
database, including inserting, updating, upserting, deleting, and undeleteing

• Apex is a strongly typed language, which means that variables must be declared with a specific data
type, such as Integer or String

Initialzing And Using A List In Apex

In Apex, you can create a new list by using the new keyword and specifying the data type of the
elements in the list. For example:

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

This creates an empty list of strings.

• You can also initialize a list with elements by using the new keyword and specifying the elements in
curly braces. For example:

List<String> colors = new List<String> { 'red', 'green', 'blue' };

This creates a new list of strings with three elements: "red", "green", and "blue".

• You can also create a list and add elements to it later using the add method. For example:
List<String> moreColors = new List<String>();
moreColors.add('orange');
moreColors.add('purple');

This creates a new empty list of strings, and then adds the elements "orange" and "purple" to it.

• You can retrieve elements from a list using the get method or the [] operator. For example:

String color1 = moreColors.get(0);


String color2 = moreColors[0];

The get method retrieves the element at the specified index position, and the [] operator also retrieves the
element at the specified index position. In this example, color1 and color2 will both be set to the first element in
the list, "orange".

• You can also iterate over a list to read its elements using a for loop. For example:

for(Integer i=0;i<colors.size();i++) {
System.debug(colors[i]);
}

This for loop will iterate over the colors list and write the value of each element to the debug log.

Email Manager Class

public class EmailManager {

// Public method

public void sendMail(String address, String subject, String body) {

// Create an email message object

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

String[] toAddresses = new String[] {address};

mail.setToAddresses(toAddresses);

mail.setSubject(subject);

mail.setPlainTextBody(body);

// Pass this email message to the built-in sendEmail method


// of the Messaging class

Messaging.SendEmailResult[] results = Messaging.sendEmail(

new Messaging.SingleEmailMessage[] { mail });

// Call a helper method to inspect the returned results

inspectResults(results);

// Helper method

private static Boolean inspectResults(Messaging.SendEmailResult[] results) {

Boolean sendResult = true;

// sendEmail returns an array of result objects.

// Iterate through the list to inspect results.

// In this class, the methods send only one email,

// so we should have only one result.

for (Messaging.SendEmailResult res : results) {

if (res.isSuccess()) {

System.debug('Email sent successfully');

else {

sendResult = false;

System.debug('The following errors occurred: ' + res.getErrors());

return sendResult;

}
The EmailManager class is an example of a custom Apex class that has a public method called sendMail
that sends an email using the Salesforce Messaging class.

The sendMail method has three parameters: address, subject, and body. These represent the email
address to send the email to, the subject of the email, and the body of the email, respectively.

The method starts by creating an instance of the Messaging.SingleEmailMessage class and assigning it to
the mail variable. This class represents a single email message and has methods for setting the various
properties of the email, such as the recipient address, subject, and body.

Next, the method creates an array of strings called toAddresses and assigns the address parameter to
the first element of the array. This array is used to specify the recipient of the email.

The method then sets the email's recipient address using the setToAddresses method of the mail object,
passing in the toAddresses array. It also sets the email's subject and body using the setSubject and
setPlainTextBody methods of the mail object, passing in the subject and body parameters, respectively.

Finally, the method calls the Messaging.sendEmail method to send the email. This method expects an
array of Messaging.SingleEmailMessage objects as an input, so the mail object is passed in as an array
with a single element. The method returns an array of Messaging.SendEmailResult objects, which are
stored in the results variable.

The method then calls a helper method called inspectResults and passes in the results array. This
method iterates over the results array and checks whether the send operation was successful or not. If
the send was successful, it writes a message to the debug log. If the send was not successful, it sets the
sendResult variable to false and writes the errors to the debug log. The inspectResults method returns
the value of the sendResult variable.
Get Started with Apex- Challenge
Challenge Question

Create an Apex class with a method that returns a list of strings

Create an Apex class with a method that returns a list of formatted strings. The length of the list is
determined by an integer parameter. You can also use an array if you prefer, but these instructions
assume you’re using a list.

• The Apex class must be called StringArrayTest and be in the public scope

• The Apex class must have a public static method called generateStringArray

• The generateStringArray method must return a list of strings

• The method must accept an incoming Integer as a parameter, which will be used to determine
the number of returned strings

• The method must return a list of strings. Each element in the list must have the format Test n,
where n is the index of the current string in the list. For example, if the input is 3, then the output should
be ['Test 0', 'Test 1', 'Test 2']. Remember that in Apex, the index position of the first element in a list is
always 0.

Here is an example of an Apex class called StringArrayTest that has a public static method called
generateStringArray that meets the requirements you provided:

Challenge Answer

public class StringArrayTest {

// Public static method that returns a list of strings

public static List<String> generateStringArray(Integer numStrings) {

// Create a new list of strings

List<String> stringList = new List<String>();


// Use a for loop to iterate over the range of integers from 0 to numStrings-1

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

// Add a formatted string to the list for each iteration

stringList.add('Test ' + i);

// Return the list of strings

return stringList;

To test this method, you can call it from another Apex class or trigger and pass in an integer value as the
parameter. For example:

List<String> testList = StringArrayTest.generateStringArray(3);

System.debug(testList); // Output: ['Test 0', 'Test 1', 'Test 2']

System.debug is a method in Apex that can be used to write messages to the debug log. The debug log is
a tool that records information about the execution of Apex code, including the values of variables and
the results of method calls. The debug log can be useful for debugging and troubleshooting Apex code

Use sObjects

In Apex, an sObject is a representation of a Salesforce record that can be used to access and manipulate
the data in that record. Every record in Salesforce has a corresponding sObject in Apex, such as an
Account sObject for an Account record. sObjects can be created and manipulated in Apex using the
sObject class and its methods.

To create an sObject in Apex, you can declare a variable with the sObject data type and assign an
sObject instance to it using the new operator. For example:

Account acct = new Account();

This creates an empty Account sObject and assigns it to the acct variable. You can then add fields to the
sObject using the constructor or dot notation. For example:
// Using the constructor

Account acct = new Account(Name='Acme', Phone='(415)555-1212', NumberOfEmployees=100);

// Using dot notation

Account acct = new Account();

acct.Name = 'Acme';

acct.Phone = '(415)555-1212';

acct.NumberOfEmployees = 100;

Once you have created and populated an sObject, you can use DML statements to insert, update,
upsert, delete, or undelete the record in the Salesforce database. For example:

Manipulate Records with DML


DML (Data Manipulation Language) is a set of statements in Apex that allows you to create, update,
delete, and restore records in Salesforce. DML statements can be used to perform these operations on a
single record or a list of records.

Insert
To insert a record using DML, you can create an sObject instance and assign values to its fields, then use
the insert statement to persist the record in the database. For example:

Account acct = new Account(Name='Acme', Phone='(415)555-1212', NumberOfEmployees=100);


insert acct;

Update
To update a record using DML, you can retrieve the record from the database, modify its field values,
and then use the update statement to persist the changes. For example:

Account acct = [SELECT Id, Name, Phone FROM Account WHERE Name = 'Acme' LIMIT 1];
acct.Phone = '(415)555-1213';
update acct;
Upsert

The upsert statement allows you to either update an existing record or insert a new one, depending on
whether a record with the specified field value already exists. You can use the upsert statement with a
list of records and specify a field to use for matching. For example:

List<Account> accts = new List<Account> {


new Account(Name='Acme', Phone='(415)555-1212', NumberOfEmployees=100),
new Account(Name='ABC Corp', Phone='(415)555-1213', NumberOfEmployees=200)
};
upsert accts Account.Name;

Delete and Undelete

The delete and undelete statements allow you to delete or restore records from the recycle bin,
respectively. You can use these statements with a single record or a list of records. For example:

Account acct = [SELECT Id, Name, Phone FROM Account WHERE Name = 'Acme' LIMIT 1];

delete acct;

List<Account> delAccts = [SELECT Id, Name FROM Account WHERE IsDeleted = true];

Undelete delAccts;

Exercises

• This example shows how to get the ID on the sObject that corresponds to the inserted account.

// Create the account sObject

Account acct = new Account(Name='Acme', Phone='(415)555-1212', NumberOfEmployees=100);


// Insert the account by using DML

insert acct;

// Get the new ID on the inserted sObject argument

ID acctID = acct.Id;

// Display this ID in the debug log

System.debug('ID = ' + acctID);

// Debug log result (the ID will be different in your case)

// DEBUG|ID = 001D000000JmKkeIAF

Execute this snippet in the Developer Console using Anonymous Apex.

// Create a list of contacts

List<Contact> conList = new List<Contact> {

new Contact(FirstName='Joe',LastName='Smith',Department='Finance'),

new Contact(FirstName='Kathy',LastName='Smith',Department='Technology'),

new Contact(FirstName='Caroline',LastName='Roth',Department='Finance'),

new Contact(FirstName='Kim',LastName='Shain',Department='Education')};

// Bulk insert all contacts with one DML call

insert conList;

// List to hold the new contacts to update

List<Contact> listToUpdate = new List<Contact>();

// Iterate through the list and add a title only

// if the department is Finance

for(Contact con : conList) {

if (con.Department == 'Finance') {
con.Title = 'Financial analyst';

// Add updated contact sObject to the list.

listToUpdate.add(con);

// Bulk update all contacts with one DML call

update listToUpdate;

The optional field is a field token. For example, to specify the MyExternalID field, the statement is:

upsert sObjectList Account.Fields.MyExternalId;

Upsert uses the sObject record's primary key (the ID), an idLookup field, or an external ID field to
determine whether it should create a new record or update an existing one:

• If the key is not matched, a new object record is created.

• If the key is matched once, the existing object record is updated.

• If the key is matched multiple times, an error is generated and the object record is neither
inserted or updated.

This example shows how upsert updates an existing contact record and inserts a new contact in one call.
This upsert call updates the existing Josh contact and inserts a new contact, Kathy.

// Insert the Josh contact

Contact josh = new Contact(FirstName='Josh',LastName='Kaplan',Department='Finance');

insert josh;

// Josh's record has been inserted

// so the variable josh has now an ID

// which will be used to match the records by upsert

josh.Description = 'Josh\'s record has been updated by the upsert operation.';

// Create the Kathy contact, but don't persist it in the database

Contact kathy = new Contact(FirstName='Kathy',LastName='Brown',Department='Technology');


// List to hold the new contacts to upsert

List<Contact> contacts = new List<Contact> { josh, kathy };

// Call upsert

upsert contacts;

// Result: Josh is updated and Kathy is created.

Execute this snippet in the Execute Anonymous window of the Developer Console

Contact jane = new Contact(FirstName='Jane',

LastName='Smith',

Email='jane.smith@example.com',

Description='Contact of the day');

insert jane;

// 1. Upsert using an idLookup field

// Create a second sObject variable.

// This variable doesn’t have any ID set.


Contact jane2 = new Contact(FirstName='Jane',
LastName='Smith',
Email='jane.smith@example.com',
Description='Prefers to be contacted by email.');
// Upsert the contact by using the idLookup field for matching.
upsert jane2 Contact.fields.Email;
// Verify that the contact has been updated
System.assertEquals('Prefers to be contacted by email.',
[SELECT Description FROM Contact WHERE Id=:jane.Id].Description);

If insert was used in this example instead of upsert, a duplicate Jane Smith contact would have been
inserted.
Merge
The merge statement in Apex allows you to merge up to three records of the same object type into one
record. The resulting record is the target record, and the two remaining records are called the master
record and the duplicate record. The target record retains its original record ID, while the master and
duplicate records are deleted.

The merge statement has the following syntax:

merge record1 record2 targetRecord;

where record1 and record2 are the records to be merged, and targetRecord is the resulting record after
the merge.

The merge statement has a number of rules and considerations to keep in mind:

The records being merged must be of the same object type.

The target record must be specified as the last parameter.

The master record is the record that retains its field values. If a field value exists in both the master and
duplicate records, the master record value is used in the merged record.

If a field is unique, such as a name or email field, it must be the same in all three records.

If a field is not specified in the target record, its value is taken from the master record.

If a field is specified in the target record but not in the master or duplicate records, it is preserved in the
merged record.

Here is an example of how to use the merge statement in Apex:

Account record1 = new Account(Name='Acme', Phone='(415)555-1212',


NumberOfEmployees=100);
Account record2 = new Account(Name='Acme', Phone='(415)555-1213',
NumberOfEmployees=200);
Account targetRecord = new Account(Name='Acme', Phone='(415)555-1214',
NumberOfEmployees=300);
insert record1;
insert record2;
merge record1 record2 targetRecord;

In this example, record1 and record2 are merged into targetRecord, and record1 and record2 are
deleted. The resulting targetRecord has the following field values:

Name: Acme
Phone: (415)555-1214
NumberOfEmployees: 300

It is important to note that the merge statement is not reversible, as the master and duplicate records
are permanently deleted after the merge. Therefore, it is recommended to use this statement with
caution and to make sure that you have a backup of your data in case of any unexpected results.

DML Statement Exceptions

If a DML operation fails, it returns an exception of type DmlException. You can catch exceptions in your
code to handle error conditions.

This example produces a DmlException because it attempts to insert an account without the required
Name field. The exception is caught in the catch block.

try {

// This causes an exception because

// the required Name field is not provided.

Account acct = new Account();

// Insert the account

insert acct;

} catch (DmlException e) {

System.debug('A DML exception has occurred: ' +

e.getMessage());

Database Methods
Apex contains the built-in Database class, which provides methods that perform DML operations and
mirror the DML statement counterparts.

These Database methods are static and are called on the class name.

• Database.insert()

• Database.update()

• Database.upsert()

• Database.delete()

• Database.undelete()

• Database.merge()

Unlike DML statements, Database methods have an optional allOrNone parameter that allows you to
specify whether the operation should partially succeed. When this parameter is set to false, if errors
occur on a partial set of records, the successful records will be committed and errors will be returned for
the failed records. Also, no exceptions are thrown with the partial success option.

This is how you call the insert method with the allOrNone set to false.

Database.insert(recordList, false);

The Database methods return result objects containing success or failure information for each record.
For example, insert and update operations each return an array of Database.SaveResult objects.

Database.SaveResult[] results = Database.insert(recordList, false);

Manipulate Records with DML-Challenge

Create a method for inserting accounts.


To pass this challenge, create an Apex class that inserts a new account named after an incoming parameter. If
the account is successfully inserted, the method should return the account record. If a DML exception occurs,
the method should return null.

 The Apex class must be called AccountHandler and be in the public scope


 The Apex class must have a public static method called insertNewAccount
 The method must accept an incoming string as a parameter, which will be used to create the
Account name
 The method must insert the account into the system and then return the record
 The method must also accept an empty string, catch the failed DML and then return null

public class AccountHandler {


public static Account insertNewAccount(String accountname){
try{
Account newAccount= new Account(Name=accountname);
insert newAccount;
Return newAccount;
}
catch(DmlException e) {
System.debug('A DML exception has occurred: ' +
e.getMessage());
Return null;
}
}
}

Write SOQL Queries


SOQL (Salesforce Object Query Language) is a query language used to search for and retrieve data from
Salesforce objects. Objects are database tables that store data specific to your organization, such as
accounts, contacts, and opportunities.

SOQL allows you to retrieve data from a single object or multiple related objects in a single query. You
can use SOQL in Apex code, Visualforce pages, and the Salesforce REST API.

SOQL is used to retrieve data from Salesforce objects, such as accounts, contacts, and opportunities.

A basic SOQL query has the following structure:

SELECT FIELD1, FIELD2, FIELD3


FROM OBJECT
WHERE CONDITION

For example, the following query retrieves the Name and Phone fields of all accounts where the
BillingCity field is "San Francisco":

SELECT N AME , PHONE


FROM ACCOUNT
WHERE B ILLING CITY = 'SAN FRANCISCO '

You can use the LIMIT clause to specify the maximum number of records to return in a query:

SELECT N AME , PHONE


FROM ACCOUNT
WHERE B ILLING CITY = 'SAN FRANCISCO '
LIMIT 10

You can use the ORDER BY clause to specify the order in which records are returned in a query:

SELECT N AME , PHONE


FROM ACCOUNT
WHERE B ILLING CITY = 'SAN FRANCISCO '
ORDER BY NAME ASC

The ASC keyword specifies ascending order (A to Z), and the DESC keyword specifies descending order (Z
to A).

You can use the AND and OR operators to combine multiple conditions in a WHERE clause:

SELECT N AME , PHONE

FROM ACCOUNT
WHERE (B ILLING CITY = 'S AN FRANCISCO' AND NUMBEROFEMPLOYEES > 50) OR (B ILLING CITY = 'LOS
ANGELES' AND NUMBEROFEMPLOYEES > 25)

You can use subqueries to retrieve related records in a single query. For example, the following query
retrieves all accounts and their related contacts:

SELECT N AME , (SELECT F IRSTNAME , LAST NAME FROM C ONTACTS)


FROM ACCOUNT

You can use the IN operator to specify multiple values for a single field in a WHERE clause:

SELECT N AME , PHONE


FROM ACCOUNT
WHERE B ILLING CITY IN ('S AN FRANCISCO', 'LOS ANGELES')

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy