0% found this document useful (0 votes)
6 views6 pages

Trigger Usecases For Interview Practice

The document outlines various Apex triggers and classes in Salesforce to manage account and contact records. It includes triggers to prevent deletion of active accounts, enforce mandatory email and phone fields for contacts, assign annual revenue based on industry, ensure contacts are associated with accounts, and synchronize contact details with account information. Additionally, it details a trigger to update the number of contacts associated with an account during various operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views6 pages

Trigger Usecases For Interview Practice

The document outlines various Apex triggers and classes in Salesforce to manage account and contact records. It includes triggers to prevent deletion of active accounts, enforce mandatory email and phone fields for contacts, assign annual revenue based on industry, ensure contacts are associated with accounts, and synchronize contact details with account information. Additionally, it details a trigger to update the number of contacts associated with an account during various operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Trigger Interview Practice

Usecases in Salesforce

Kajal Yadav
Trigger Practices 1
1) Create a Trigger To Prevent the deletion of an Active Account Record

Apex Trigger (AccountTrigger)

trigger AccountTrigger on Account (before delete) {


AccountTriggerHandler.preventActiveAccountDeletion(Trigger.old);
}

Apex Class (AccountTriggerHandler)

public class AccountTriggerHandler {


public static void preventActiveAccountDeletion(List<Account> oldAccounts) {
for (Account acc : oldAccounts) {
if (acc.IsActive__c == true) {
acc.addError('You cannot delete an Active Account.');
}
}
}
}

2) Create a Trigger on Contact Object, to make the Email and Phone Fields
should be Manadatory upon creating or updating a Contact Record.

Apex Trigger (ContactDetailsValidationTrigger)

trigger ContactDetailsValidationTrigger on Contact (before insert, before update) {


ContactMandatoryFieldsHandler.validateMandatoryFields(Trigger.new);
}

Apex Class (ContactDetailsValidationHandler)

public class ContactDetailsValidationHandler {


public static void validateMandatoryFields(List<Contact> contacts) {
for (Contact con : contacts) {
// Skip records that are already marked with an error
if (con == null || con.Email == null || con.Email.trim() == '' ||
con.Phone == null || con.Phone.trim() == '') {

con.addError('Both Email and Phone fields are required.');


}
}
}
}

3) Create a Trigger on Account Object, To assign the Annualrevenue value


as below.
Industry Name Annualrevenue
----------------------------------------------------------------
Banking ----> 5000000
Finance ----> 4000000
Trigger Practices 2
Insurance ----> 3500000
Healthcare ----> 2500000
Else ----> 500000

Apex Trigger (SetAnnualRevenueTrigger)

trigger SetAnnualRevenueTrigger on Account (before insert, before update) {


SetAnnualRevenueHandler.assignAnnualRevenue(Trigger.new);
}

Apex Class (SetAnnualRevenueHandler)

public class SetAnnualRevenueHandler {


public static void assignAnnualRevenue(List<Account> accountList) {
for (Account acc : accountList) {
if (acc.Industry == null) {
acc.AnnualRevenue = 500000;
continue;
}

switch on acc.Industry.toLowerCase() {
when 'banking' {
acc.AnnualRevenue = 5000000;
}
when 'finance' {
acc.AnnualRevenue = 4000000;
}
when 'insurance' {
acc.AnnualRevenue = 3500000;
}
when 'healthcare' {
acc.AnnualRevenue = 2500000;
}
when else {
acc.AnnualRevenue = 500000;
}
}
}
}
}

4) Create a Trigger, to make sure Each Contact Should be get associated


with an Account

Apex Trigger (ContactAccountValidationTrigger)

trigger ContactAccountValidationTrigger on Contact (before insert, before update) {


ContactAccountValidationHandler.ensureAccountAssociation(Trigger.new);
}
Trigger Practices 3
Apex Class (ContactAccountValidationHandler)

public class ContactAccountValidationHandler {


public static void ensureAccountAssociation(List<Contact> contacts) {
for (Contact con : contacts) {
if (con.AccountId == null) {
con.addError('Each Contact must be associated with an Account.');
}
}
}
}

5) Write a Trigger, to Prevent the Deletion of the Associated contacts upon


removing the Account record

Apex Trigger (SetAnnualRevenueTrigger)

trigger PreventAccountWithContactsDeletionTrigger on Account (before delete) {

PreventAccountWithContactsDeletionHandler.preventDeletionIfHasContacts(Tri
gger.old);
}

Apex Class (ContactAccountValidationHandler)

public class PreventAccountWithContactsDeletionHandler {


public static void preventDeletionIfHasContacts(List<Account> accountList) {
Set<Id> accountIds = new Set<Id>();

for (Account acc : accountList) {


if (acc.Id != null) {
accountIds.add(acc.Id);
}
}

// Query contacts related to the accounts being deleted


Map<Id, List<Contact>> accountToContactsMap = new Map<Id,
List<Contact>>();
for (Contact con : [SELECT Id, AccountId FROM Contact WHERE AccountId IN
:accountIds]) {
if (!accountToContactsMap.containsKey(con.AccountId)) {
accountToContactsMap.put(con.AccountId, new List<Contact>());
}
accountToContactsMap.get(con.AccountId).add(con);
}

// Prevent deletion if any related contacts exist


for (Account acc : accountList) {
if (accountToContactsMap.containsKey(acc.Id)) {
acc.addError('Cannot delete Account record that has associated Contacts.');
}
Trigger Practices 4
}
}
}

6) Write an Apex Trigger, to synchronize the Contact Record's Phone and


Fax value with the associated Account Record's Phone and Fax Numbers.

Apex Trigger (SyncContactWithAccountTrigger)

trigger SyncContactWithAccountTrigger on Contact (before insert, before update) {


SyncContactWithAccountHandler.syncPhoneAndFax(Trigger.new);
}

Apex Class (SyncContactWithAccountHandler)

public class SyncContactWithAccountHandler {


public static void syncPhoneAndFax(List<Contact> contactList) {
Set<Id> accountIds = new Set<Id>();

// Collect all unique AccountIds from Contacts


for (Contact con : contactList) {
if (con.AccountId != null) {
accountIds.add(con.AccountId);
}
}

if (accountIds.isEmpty()) return;

// Query relevant Accounts


Map<Id, Account> accountMap = new Map<Id, Account>(
[SELECT Id, Phone, Fax FROM Account WHERE Id IN :accountIds]
);

// Sync Account's Phone and Fax to Contact


for (Contact con : contactList) {
if (con.AccountId != null && accountMap.containsKey(con.AccountId)) {
Account acc = accountMap.get(con.AccountId);
con.Phone = acc.Phone;
con.Fax = acc.Fax;
}
}
}
}

7) Create a trigger on the Contact object to automatically update the custom field
Number_of_Contacts__c on the related Account whenever a Contact is inserted,
updated, deleted, or undeleted.

Apex Trigger (UpdateNoOfContacts)

trigger UpdateNoOfContacts on Account (after insert, after update, after delete, after
Trigger Practices 5
undelete) {
if (Trigger.isAfter) {
if (Trigger.isInsert || Trigger.isUpdate || Trigger.isDelete || Trigger.isUndelete) {
UpdateNoOfContactsHandler.handleContacts(Trigger.new, Trigger.oldMap,
Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, Trigger.isUndelete);
}
}
}

Apex Class (UpdateNoOfContactsHandler)

public class UpdateNoOfContactsHandler {


public static void handleContacts(List<Contact> newContacts, Map<Id, Contact>
oldContactMap, Boolean isInsert, Boolean isUpdate, Boolean isDelete, Boolean
isUndelete) {
Set<Id> accountIds = new Set<Id>();

if ((isInsert || isUpdate) && newContacts != null) {


for (Contact contactRecord : newContacts) {
accountIds.add(contactRecord.AccountId);
}
}
if ((isDelete || isUndelete) && oldContactMap != null) {
for (Contact contactRecord : oldContactMap.values()) {
accountIds.add(contactRecord.AccountId);
}
}
updateAccountNumberOfContacts(accountIds);
}
private static void updateAccountNumberOfContacts(Set<Id> accountIds) {
List<Account> accountsToUpdate = [SELECT Id, Number_of_Contacts__c,(SELECT Id
FROM Contacts) FROM Account WHERE Id IN :accountIds];
Map<Id, Integer> accountContactCountMap = new Map<Id, Integer>();
for (Account acc : accountsToUpdate) {
Integer contactCount = acc.Contacts.size();

acc.Number_of_Contacts__c = contactCount;
accountContactCountMap.put(acc.Id, contactCount);
}

update accountsToUpdate;
}
}

Trigger Practices 6

You might also like