Example Apex Codes
Example Apex Codes
if (Trigger.isUpdate || Trigger.isDelete) {
for (Contact con: Trigger.old) {
if (con.AccountId != null) {
accountIds.add(con.AccountId);
}
}
}
update accountsToUpdate;
}
}
###################################################################################
##################################################################################
// Apex Trigger and method to check if an Account has related Contacts. If none
exist, it creates a default Contact.
ContactHelper.ensureDefaultContact(accountIds);
}
ContactHelper.ensureDefaultContact(accountIds);
}
Approach 1: Better
public class ContactHelper {
public static void ensureDefaultContact(Set<Id> accountIds) {
if (accountIds == null || accountIds.isEmpty()) {
return; // Exit if no Account IDs are provided
}
// Query existing Contacts and remove their AccountIds from the set
for (AggregateResult ar : [SELECT AccountId FROM Contact WHERE AccountId
IN: accountIds GROUP BY AccountId]) {
accountIds.remove((Id) ar.get('AccountId')); // Remove Accounts that
already have Contacts
}
if (!contactsToInsert.isEmpty()) {
insert contactsToInsert;
}
}
}
###################################################################################
##################################################################################
if (!accountIds.isEmpty()) {
// Fetch the latest Opportunity Stage for each Account
Map<Id, String> accountStageMap = new Map<Id, String>();
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate;
}
}
}
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate;
}
}
###################################################################################
##################################################################################
// Apex trigger to update the Account object's Description field with a comma-
separated list of related Opportunity names and update Total_Amount__c
// with the sum of all related Opportunity amounts.
if (Trigger.isDelete) {
for (Opportunity opp: Trigger.old) {
if (opp.AccountId != null) {
accountIds.add(opp.AccountId);
}
}
}
if (!accountIds.isEmpty()) {
OpportunityHelper.updateAccountFields(accountIds);
}
}
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate;
}
}
}
###################################################################################
##################################################################################
// Method to return the accountId and the total Paid Payment value from the related
Payment object to the related Opportunity object of the Account
return accountPaymentMap;
}
}
###################################################################################
##################################################################################
###################################################################################
##################################################################################
if (!accIds.isEmpty()) {
// Query only necessary fields and store in a Map for quick lookup
Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id, Rating,
Description FROM Account WHERE Id IN: accIds]);
###################################################################################
##################################################################################
###################################################################################
##################################################################################
// Apex method to find duplicates in a list of strings and count how many times
each string appears
public static Map<String, Integer> findDuplicates(List<String> strList) {
Map<String, Integer> countMap = new Map<String, Integer>();
return countMap;
}
###################################################################################
##################################################################################
// Trigger:
trigger AccountUpdateFromContact on Contact (after insert, after update) {
if (Trigger.isInsert || Trigger.isUpdate) {
ContactTriggerHandler.updateAccountContacts(Trigger.newMap,
Trigger.oldMap);
}
}
// Handler Class:
public class ContactTriggerHandler {
public static void updateAccountContacts(Map<Id, Contact> newContactMap,
Map<Id, Contact> oldContactMap) {
if (newContactMap == null || newContactMap.isEmpty()) {
return; // Exit if no contacts to process
}
###################################################################################
##################################################################################
// Trigger:
trigger ContactTrigger on Contact (after undelete, before delete, after insert,
after update, after delete) {
Set<Id> contactIds = new Set<Id>();
if (Trigger.isDelete || Trigger.isUndelete) {
for (Contact c : (Trigger.isDelete ? Trigger.old: Trigger.new)) {
contactIds.add(c.Id);
}
}
if (Trigger.isDelete) {
deleteRelatedActionPlans(contactIds);
}
if (Trigger.isUndelete) {
undeleteRelatedActionPlans(contactIds);
}
}
if (!actionPlansToDelete.isEmpty()) {
Database.emptyRecycleBin(actionPlansToDelete);
}
try {
if (!actionPlansToUndelete.isEmpty()) {
Database.undelete(actionPlansToUndelete, false);
}
} catch (DmlException e) {
for (Contact c: Trigger.new) {
c.addError('You cannot undelete an Action Plan whose related Contact is
deleted.');
}
}
}
###################################################################################
##################################################################################
// Write a batch class to update the MailingCity and MailingCountry fields of
Contact records based on the BillingCity and BillingCountry of their
// parent Account records.
// Aura Component:
<aura:component controller="createAccountRecords" implements="force:appHostable,
flexipage:availableForAllPageTypes, forceCommunity:AvailableForAllPageTypes,
force:hasRecordId" access="global">
<div class="slds-p-around_small">
<lightning:input type="Text" label="Name" value="{!v.createAcc.Name}"/>
<lightning:input type="Text" label="Account Number" value="{!
v.createAcc.AccountNumber}"/>
<lightning:input type="Phone" label="Phone Number" value="{!
v.createAcc.Phone}"/>
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
component.set('v.ratingList', response.getReturnValue());
} else if (state === "ERROR") {
console.error('Error fetching picklist values:',
response.getError());
}
});
$A.enqueueAction(action);
},
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
alert('Account created successfully!');
$A.enqueueAction(action);
},
@AuraEnabled
public static List<String> getPickList(String objName, String fldName) {
List<String> pkList = new List<String>();
try {
// Get object schema
Map<String, Schema.SObjectType> allObj = Schema.getGlobalDescribe();
if (!allObj.containsKey(objName)) {
throw new Exception('Invalid object name: ' + objName);
}
} catch (Exception e) {
System.debug('Error fetching picklist: ' + e.getMessage());
}
return pkList;
}
@AuraEnabled
public static List<Account> createAccounts(List<Account> accList) {
List<Account> insertedAccounts = new List<Account>();
try {
insert accList;
insertedAccounts = accList;
} catch (DmlException e) {
System.debug('Error inserting accounts: ' + e.getMessage());
throw new AuraHandledException('Failed to create accounts: ' +
e.getDmlMessage(0));
}
return insertedAccounts;
}
}