Trining Final 1 Apex
Trining Final 1 Apex
• 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
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:
• You can also initialize a list with elements by using the new keyword and specifying the elements in
curly braces. For example:
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:
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.
// Public method
mail.setToAddresses(toAddresses);
mail.setSubject(subject);
mail.setPlainTextBody(body);
inspectResults(results);
// Helper method
if (res.isSuccess()) {
else {
sendResult = false;
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 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 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
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:
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:
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
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:
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:
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:
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.
insert acct;
ID acctID = acct.Id;
// DEBUG|ID = 001D000000JmKkeIAF
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')};
insert conList;
if (con.Department == 'Finance') {
con.Title = 'Financial analyst';
listToUpdate.add(con);
update listToUpdate;
The optional field is a field token. For example, to specify the MyExternalID field, the statement is:
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 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 josh;
// Call upsert
upsert contacts;
Execute this snippet in the Execute Anonymous window of the Developer Console
LastName='Smith',
Email='jane.smith@example.com',
insert jane;
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.
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 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.
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.
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 {
insert acct;
} catch (DmlException e) {
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.
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.
For example, the following query retrieves the Name and Phone fields of all accounts where the
BillingCity field is "San Francisco":
You can use the LIMIT clause to specify the maximum number of records to return in a query:
You can use the ORDER BY clause to specify the order in which records are returned in a query:
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:
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:
You can use the IN operator to specify multiple values for a single field in a WHERE clause: