Apex Integration
Callouts to
External Services
Apex can make HTTP callouts to integrate with
external web services.
public class CalloutExample {
@future(callout=true)
public
static void makeCallout() {
Http
http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.example.com/data');
request.setMethod('GET');
HttpResponse response = http.send(request);
System.debug(response.getBody());
}
}
Handling
Callout Responses
Handle responses from external services and process
them.
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
//
Process response
} else {
// Handle
error
}
Using Named
Credentials
Named credentials simplify callouts by storing
authentication details securely.
Assignment: Write an
Apex class to make a callout to a public API (e.g., a weather API) and print
the response. Use named credentials for authentication if needed.
Apex
Design Patterns
Singleton
Pattern
Ensure a class has only one instance.
public class SingletonExample {
private
static SingletonExample instance;
private
SingletonExample() {}
public
static SingletonExample getInstance() {
if
(instance == null) {
instance = new SingletonExample();
}
return
instance;
}
}
Factory
Pattern
Create objects without specifying the exact class.
public class ShapeFactory {
public
Shape getShape(String shapeType) {
if
(shapeType == 'Circle') {
return new Circle();
} else if (shapeType == 'Square') {
return new Square();
}
return null;
}
}
public interface Shape {
void
draw();
}
public class Circle implements Shape {
public
void draw() {
System.debug('Drawing Circle');
}
}
public class Square implements Shape {
public
void draw() {
System.debug('Drawing Square');
}
}
Assignment: Implement a singleton pattern
for a logging utility class that logs messages to a custom object. Also, create
a factory pattern to generate different types of logs (e.g., info, error).
Advanced
SOQL and SOSL
Complex
Queries with SOQL
Use complex queries to filter and sort data.
List<Account> accounts = [SELECT Id, Name
FROM Account WHERE CreatedDate > LAST_N_DAYS:30];
Using SOSL
for Full-Text Search
SOSL is used for full-text searches.
List<List<sObject>> searchResults =
[FIND 'Acme' IN ALL FIELDS RETURNING Account(Id, Name), Contact(Id, Name)];
Performance
Considerations
- Use indexed fields in WHERE clauses.
- Limit the number of records returned.
Assignment: Write a
SOQL query to find all contacts related to accounts created in the last 30
days. Use SOSL to search for a keyword across multiple objects.
Advanced
Triggers and Trigger Frameworks
Writing
Complex Triggers
Implement complex logic in triggers using context
variables.
trigger ComplexTrigger on Account (before insert,
before update) {
if
(Trigger.isBefore) {
if
(Trigger.isInsert) {
// Logic for before insert
}
else if (Trigger.isUpdate) {
// Logic for before update
}
}
}
Trigger
Frameworks and Patterns
Use a trigger handler class to organize and
modularize your code.
trigger AccountTrigger on Account (before insert,
before update) {
if
(Trigger.isBefore) {
if
(Trigger.isInsert) {
AccountTriggerHandler.beforeInsert(Trigger.new);
}
else if (Trigger.isUpdate) {
AccountTriggerHandler.beforeUpdate(Trigger.new, Trigger.oldMap);
}
}
}
public class AccountTriggerHandler {
public
static void beforeInsert(List<Account> newAccounts) {
for
(Account acc : newAccounts) {
acc.Description = 'New Account';
}
}
public
static void beforeUpdate(List<Account> newAccounts, Map<Id,
Account> oldMap) {
for
(Account acc : newAccounts) {
if (acc.Name != oldMap.get(acc.Id).Name) {
acc.Description = 'Account Name Updated';
}
}
}
}
Assignment: Implement
a trigger handler framework for a Contact trigger that handles both insert and update events.
Security
in Apex
Enforcing
Sharing Rules
Use the with sharing keyword to enforce sharing rules.
public with sharing class SharingExample {
// Class
logic that respects sharing rules
}
Field-Level
Security and Object Permissions
Check field-level security and object permissions
programmatically.
// Check field-level security
Schema.SObjectType accountSchema =
Schema.getGlobalDescribe().get('Account');
Schema.SObjectField nameField =
accountSchema.getDescribe().fields.getMap().get('Name');
if (nameField.getDescribe().isAccessible()) {
// Field
is accessible
}
// Check object-level permissions
if (accountSchema.getDescribe().isCreateable()) {
// Object
is createable
}
Securing
Apex Code
- Avoid SOQL injection by using binding variables.
- Validate user inputs.
Assignment: Write a
class that enforces sharing rules and checks field-level security before
updating a field on the Account object.
Custom
Metadata and Custom Settings
Using Custom
Metadata Types
Custom metadata types are used to define
application configuration data.
CustomMetadataType__mdt metadataRecord = [SELECT
Field__c FROM CustomMetadataType__mdt WHERE DeveloperName = 'MyRecord'];
System.debug(metadataRecord.Field__c);
Custom
Settings (Hierarchy and List)
Custom settings are similar to custom objects and
are used to create and manage custom data.
// Hierarchy Custom Setting
MySetting__c settings =
MySetting__c.getInstance(UserInfo.getUserId());
System.debug(settings.Some_Field__c);
// List Custom Setting
List<MySetting__c> settingsList =
MySetting__c.getAll().values();
Assignment: Create a
custom metadata type for storing configuration settings. Write an Apex class to
retrieve and use these settings in your application.
Dynamic
Apex
Dynamic SOQL
and DML
Dynamic SOQL and DML allow you to construct queries
and manipulate data at runtime.
String query = 'SELECT Id, Name FROM Account WHERE
Name = :accountName';
List<Account> accounts =
Database.query(query);
Using
sObject and Schema Classes
Use sObject and Schema classes for
dynamic operations.
sObject obj =
Schema.getGlobalDescribe().get('Account').newSObject();
obj.put('Name', 'Dynamic Account');
insert obj;
Reflection
in Apex
Use reflection to inspect classes and their
properties at runtime.
Map<String, Schema.SObjectType> schemaMap =
Schema.getGlobalDescribe();
Schema.SObjectType accountType =
schemaMap.get('Account');
Assignment: Write a
dynamic SOQL query to fetch accounts based on user input. Create a new Account object dynamically using the sObject and Schema classes.
Platform
Events and Apex
Introduction
to Platform Events
Platform events enable event-driven architecture in
Salesforce, allowing you to publish and subscribe to custom events.
Publishing
and Subscribing to Events
// Publish event
MyEvent__e event = new
MyEvent__e(Field__c='value');
Database.SaveResult sr = EventBus.publish(event);
// Subscribe to event
trigger MyEventTrigger on MyEvent__e (after insert)
{
for
(MyEvent__e event : Trigger.new) {
System.debug(event.Field__c);
}
}
Event-Driven
Architecture
Decouple components and improve system scalability
by using platform events.
Assignment: Create a
platform event for notifying when a new account is created. Write an Apex
trigger to publish the event and another to subscribe and process it.
Invocable
Apex
Creating
Invocable Methods for Flow and Process Builder
Invocable methods allow you to call Apex from Flow
and Process Builder.
public class InvocableExample {
@InvocableMethod
public
static void myInvocableMethod(List<String> input) {
for
(String s : input) {
System.debug('Invocable method input: ' + s);
}
}
}
Use Cases
for Invocable Apex
Enhance Flows and Process Builders with custom
logic and reusable business logic.
Assignment: Write an
invocable method that takes a list of account IDs and updates their
descriptions. Create a Flow to call this method.
Apex
and Lightning Components
Using Apex
with Lightning Web Components (LWCs)
Annotate Apex methods with @AuraEnabled to use them with LWCs.
apex
Copy code
public class LWCController {
@AuraEnabled(cacheable=true)
public static
List<Account> getAccounts() {
return [SELECT Id, Name FROM Account];
}
}
Apex as a
Controller for LWCs
Integrate Apex with LWCs for server-side logic.
// JavaScript in LWC
import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/LWCController.getAccounts';
export default class AccountList extends LightningElement
{
@wire(getAccounts)
accounts;
}
Best Practices for Integrating Apex with
LWCs
- Use @AuraEnabled methods
for server-side logic.
- Handle errors gracefully.
- Optimize performance by minimizing server calls.
Assignment: Create a
simple LWC that fetches and displays a list of accounts using an Apex
controller method.
For more in-depth tutorials and learning paths,
refer to the following resources:
- Trailhead Modules: https://trailhead.salesforce.com/
- Salesforce Developer Guide: https://developer.salesforce.com/docs/
- Salesforce Apex Documentation: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/
Happy learning!
0 Comments