APEX
APEX
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/
apex_intro_get_started.htm
https://www.tutorialspoint.com/apex/index.htm
What is Apex?
Apex is a strongly typed, object-oriented programming language that allows
developers to execute flow and transaction control statements on Salesforce servers
in conjunction with calls to the API. Using syntax that looks like Java and acts
like database stored procedures, Apex enables developers to add business logic to
most system events, including button clicks, related record updates, and
Visualforce pages. Apex code can be initiated by Web service requests and from
triggers on objects.
Apex
Use Apex if you want to:
Perform complex validation over multiple objects.
Create complex business processes that are not supported by workflow.
Create custom transactional logic (logic that occurs over the entire transaction,
not just with a single record or object).
Attach custom logic to another operation, such as saving a record, so that it
occurs whenever the operation is executed, regardless of whether it originates in
the user interface, a Visualforce page, or from SOAP API.
Create Web services.
Create email services.
Data Types
In Apex, all variables and expressions have a data type, such as sObject,
primitive, or enum.
A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, or
Boolean (see Primitive Data Types)
An sObject, either as a generic sObject or as a specific sObject, such as an
Account, Contact, or MyCustomObject__c
A collection, including:
A list (or array) of primitives, sObjects, user defined objects, objects created
from Apex classes, or collections (see Lists)
A set of primitives (see Sets)
A map from a primitive to a primitive, sObject, or collection (see Maps)
A typed list of values, also known as an enum (see Enums)
Objects created from user-defined Apex classes (see Classes, Objects, and
Interfaces)
Objects created from system supplied Apex classes
Null (for the null constant, which can be assigned to any variable)
Syntax
Data Type
Primitives
-----
Looping
Integer count = 1;
while(count < 11) {
System.debug('The Count is: ' + count);
count++;
}
Integer count = 1;
while(count <= 10) {
System.debug('The Count is: ' + count);
count++;
}
-------
---
----
Collections
----
Array
System.debug(colors.size());
// Array
/*
// Create an list of random numbers and then print the list elements in ascending
order
randomNumbers.sort();
System.debug(randomNumbers); */
List<String> colors = new List<String> {'green', 'red', 'blue'};
/* colors.add('red');
colors.add('blue');
colors.add('green'); */
System.debug(colors);
-----
/* This class provides methods to read, create, update and delete account records
*/
public class AccountService {
/* This method returns a list of accounts based on the name provided in the
input */
public List<Account> getAccounts(String accountName) {
List<Account> output = [SELECT Id, Name FROM Account WHERE Name
=:accountName];
if(output == null || output.size() == 0) {
System.debug('There is no account with name = ' + accountName);
} else {
System.debug(output);
}
return output;
/* This method finds account by given name and updates the accountSite field */
public void updateAccount(String accountName, String accountSite) {
List<Account> accounts = [SELECT Id, Name, Site FROM Account WHERE
Name=:accountName];
for(Account acc : accounts) {
acc.Site = accountSite;
}
update accounts;
}
/* This method deletes all accounts whose name is equal to input provided name
from user */
public void deleteAccount(String accountName) {
List<Account> accounts = [SELECT Id, Name, Site FROM Account WHERE
Name=:accountName];
if(accounts != null && accounts.size() > 0) {
delete accounts;
}
}
-------
Anonymous Window
----
https://trailhead.salesforce.com/content/learn/modules/apex_testing/
apex_testing_intro
----
test class
@isTest
public class AccountServiceTest {
@isTest(SeeAllData=true)
public static void testGetAccount() {
AccountService service = new AccountService();
List<Account> result = service.getAccounts('Edge Communications');
System.assertEquals(1, result.size());
}
@isTest()
public static void testCreateAccount() {
AccountService service = new AccountService();
Account result = service.createAccount('Tesla Cars');
System.Assert.isNotNull(result, 'Account is not null');
}
@isTest(SeeAllData=true)
public static void testUpdateAccount() {
AccountService service = new AccountService();
service.updateAccount('Dickenson plc', 'www.testme.com');
List<Account> result = service.getAccounts('Dickenson plc');
Account resultAccount = result.get(0);
System.assertEquals('www.testme.com', resultAccount.Site);
}
@isTest
public static void testDeleteAccount() {
AccountService service = new AccountService();
System.assertEquals(0, resultAfterDelete.size());
}
----
--- test
@isTest
public class CalculatorServiceTest {
@isTest
public static void testAddTwoNumbers() {
CalculatorService service = new CalculatorService();
Integer result = service.add(1, 2);
System.assertEquals(3, result);
}
@isTest
public static void testSubtractTwoNumbers() {
CalculatorService service = new CalculatorService();
Integer result = service.subtract(3, 2);
System.assertEquals(1, result);
}
}
-----
Use Case
Write an Apex class to create Task (Standard Object) record for opportunities that
are NOT closed and close date is less than TODAY and stage name is Negotiation.
if(!oppList.isEmpty()) {
for(Opportunity opp : oppList) {
Task tsk = new Task();
tsk.Subject = 'Reminder Task for Opportunity';
tsk.Priority = 'Normal';
tsk.Status = 'Not Started';
tsk.OwnerId = opp.OwnerId;
tsk.WhatId = opp.Id;
taskList.add(tsk);
}
}
// Bulkification
if(!taskList.isEmpty()) {
insert taskList;
}
}
}
--- test
@isTest()
public class OpportunityTaskServiceTest {
@isTest()
public static void testCreateTask() {
// Create an opportunity test record to match the conditions
Opportunity opp = new Opportunity();
opp.Name = 'Test Opp';
opp.StageName = 'Negotiation/Review';
opp.CloseDate = Date.newInstance(2022, 12, 9);
insert opp;