Back to Top
Showing posts with label Trigger scenario based questions salesforce. Show all posts
Showing posts with label Trigger scenario based questions salesforce. Show all posts

In Salesforce, each Account can have multiple Opportunities associated with it. We need to calculate and store the Total Closed-Won Opportunity Amount for each Account in a custom field called Total_Closed_Won_Amount__c

This field should be updated whenever any Opportunity is:

  1. Inserted (new Opportunity created)
  2. Updated (Stage changes to or from "Closed Won", or the Amount changes)
  3. Deleted (Opportunity is deleted)
  4. Undeleted (Opportunity is restored from the Recycle Bin)

trigger OpportunityTrigger on Opportunity (
    after insert, after update, after delete, after undelete
) {
    if (Trigger.isAfter) {
        OpportunityTriggerHandler.updateAccountTotals(
            Trigger.new,
            Trigger.oldMap
        );
    }
}


public class OpportunityTriggerHandler {

    public static void updateAccountTotals(
        List<Opportunity> newList,
        Map<Id, Opportunity> oldMap
    ) {
        Set<Id> accountIds = new Set<Id>();

        if (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) {
            for (Opportunity opp : newList) {
                if (opp.AccountId != null) {
                    accountIds.add(opp.AccountId);
                }
            }
        }

        if (Trigger.isUpdate || Trigger.isDelete) {
            for (Opportunity opp : oldMap.values()) {
                if (opp.AccountId != null) {
                    accountIds.add(opp.AccountId);
                }
            }
        }

        if (accountIds.isEmpty()) return;

        // 🔥 Aggregate Query
        Map<Id, Decimal> accountToTotalMap = new Map<Id, Decimal>();

        for (AggregateResult ar : [
            SELECT AccountId accId, SUM(Amount) totalAmount
            FROM Opportunity
            WHERE AccountId IN :accountIds
            AND StageName = 'Closed Won'
            GROUP BY AccountId
        ]) {
            accountToTotalMap.put(
                (Id) ar.get('accId'),
                (Decimal) ar.get('totalAmount')
            );
        }

        List<Account> accountsToUpdate = new List<Account>();

        for (Id accId : accountIds) {
            accountsToUpdate.add(new Account(
                Id = accId,
                Total_Closed_Won_Amount__c =
                    accountToTotalMap.containsKey(accId)
                    ? accountToTotalMap.get(accId)
                    : 0
            ));
        }

        if (!accountsToUpdate.isEmpty()) {
            update accountsToUpdate;
        }
    }
}


Other Common Trigger Scenarios Using Aggregate Query


Count of Contacts on Account:
    
SELECT AccountId, COUNT(Id)
FROM Contact
GROUP BY AccountId


Average Case Resolution Time per Account

SELECT AccountId, AVG(Resolution_Time__c)
FROM Case
GROUP BY AccountId

Total Order Amount on Customer:

SELECT Customer__c, SUM(Order_Amount__c)
FROM Order__c
GROUP BY Customer__c

Can we use if (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) in handler?

Ans: If your handler method is called directly from a trigger, then the Trigger context variables are still available inside the handler.

It will NOT work if:

  • The handler is called from:

    • Batch Apex

    • Queueable

    • Future method

    • Anonymous Apex

    • Unit test calling the handler directly

Can we use Trigger.isInsert inside a handler class?

Ans: Yes, technically it works if the handler is invoked from a trigger.
However, for testability, reusability, and clean architecture, it’s best practice to pass the trigger context explicitly instead of relying on Trigger.isInsert inside the handler.

Write a Trigger for whenever a Contact gets Inserted the Account should get Inserted with the same name as the Contact. And It must be the Parent of that Contact record?


    
        
trigger ContactTrigger on Contact (after insert) {
    if (Trigger.isAfter && Trigger.isInsert) {
        ContactTriggerHandler.createAccountForContacts(Trigger.new);
    }
}
        
    
    

public class ContactTriggerHandler {

    public static void createAccountForContacts(List newContacts) {
        // List to hold Account records that need to be created
        List accountsToInsert = new List();

        // Map to store the relationship between each Contact and its corresponding Account
        Map contactToAccountMap = new Map();

        // Loop through each inserted Contact record
        for (Contact con : newContacts) {
            // Create a new Account with the same name as the Contact's LastName
            Account newAccount = new Account();
            newAccount.Name = con.LastName; // You can use any field for the Account Name

            // Add the Account to the list to be inserted
            accountsToInsert.add(newAccount);

            // Store the mapping of ContactId to Account (to link them later)
            contactToAccountMap.put(con.Id, newAccount);
        }

        // Insert the Accounts
        if (!accountsToInsert.isEmpty()) {
            insert accountsToInsert;
        }

        // Now that the Accounts are inserted, we can update the Contacts to link them to the correct Account
        List contactsToUpdate = new List();

        // Loop through the newContacts again to associate Account with Contact
        for (Contact con : newContacts) {
            // Retrieve the corresponding Account from the map (the Account was inserted already)
            Account acc = contactToAccountMap.get(con.Id);

            // Create a new Contact record to update its AccountId
            Contact updatedContact = new Contact(Id = con.Id); // Specify the Id to identify the record
            updatedContact.AccountId = acc.Id;

            // Add the updated Contact to the list
            contactsToUpdate.add(updatedContact);
        }

        // Update the Contacts with the new AccountId
        if (!contactsToUpdate.isEmpty()) {
            update contactsToUpdate;
        }
    }
}


    
    



    

Ensure certain field combinations are valid before a record is saved. For instance, if one field is True, ensure another field is not Null

Posted on TimeJune 21, 2024

Let’s consider the Account object for this scenario. Imagine we create two custom fields on the Account object:

  1. Has_Services__c (Checkbox): This field serves to indicate whether an account has active services associated with it.
  2. Service_Renewal_Date__c (Date): This field is designed to store the renewal date of the services linked to the account.

    
        
trigger AccountTrigger on Account (before insert, before update) {
    if(Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)) {
        AccountTriggerHandler.handleServices(trigger.new);
    } 
}
        
    
    

public class AccountTriggerHandler {
	public static void handleServices(List newAccounts){
        for (Account acc : newAccounts) {
            // If Has_Services__c is true, ensure Service_Renewal_Date__c is not null
            if (acc.Has_Services__c && acc.Service_Renewal_Date__c == null) {
                acc.addError('Please enter the Service Renewal Date for accounts with active services.');
            }
        }
    }
}        

    
    

@isTest
private class AccountTriggerHandlerTest {
	// Test method to cover scenario where Has_Services__c is true and Service_Renewal_Date__c is null
    @isTest
    static void testAccountWithServicesAndNullRenewalDate() {
        // Create a new Account with Has_Services__c true and Service_Renewal_Date__c as null
        Account acc = new Account(
            Name = 'Test Account',
            Has_Services__c = true
            // Service_Renewal_Date__c is intentionally left null
        );

        System.Test.startTest();
        try {
            insert acc;
            // If the validation is properly set up, this should throw an error
            System.assert(false, 'Expected validation rule to prevent saving with null Service_Renewal_Date__c');
        } catch (DmlException e) {
            // Ensure the correct error message is returned
            System.assertEquals('Please specify the Service Renewal Date.', e.getDmlMessage(0));
        }
        System.Test.stopTest();
    }

    // Test method to cover scenario where Has_Services__c is false and Service_Renewal_Date__c is null
    @isTest
    static void testAccountWithoutServicesAndNullRenewalDate() {
        // Create a new Account with Has_Services__c false and Service_Renewal_Date__c as null
        Account acc = new Account(
            Name = 'Test Account',
            Has_Services__c = false
            // Service_Renewal_Date__c is intentionally left null
        );

        System.Test.startTest();
        try {
            insert acc;
            // If the validation is properly set up, this should not throw an error
            System.assert(true);
        } catch (DmlException e) {
            // If an error occurs unexpectedly, fail the test
            System.assert(false, 'Unexpected error: ' + e.getDmlMessage(0));
        }
        System.Test.stopTest();
    }

}

    

When a parent record is deleted, delete all related child records.

Posted on TimeJune 20, 2024

Let's take Account and Contact object.

    
        
trigger AccountTrigger on Account (after delete) {
    if(trigger.isAfter && trigger.isDelete) {
        AccountTriggerHandler.deleteRelatedContacts(trigger.old);
    }
}
        
    
    
        
public class AccountTriggerHandler {
    public static void deleteRelatedContacts(List oldAccounts) {
        // Collect all deleted accouts Id
        Set accIds = New Set();
        
        for(Account acc: oldAccounts){
            accIds.add(acc.Id);
        }

        if(!accIds.isEmpty()) {
            // Retrieve all related contact
            List relatedContacts = [SELECT Id FROM Contact WHERE AccountId IN: accIds];
            if(!relatedContacts.isEmpty()){
                Delete relatedContacts;
            }
        }
    }
}
        
    
    
        
@isTest
private class PracticeAccountTest {
    @isTest
    private static void testDeleteRelatedContacts() {
        Account testAccount1 = new Account(Name = 'Test Account 1');
        insert testAccount1;
        
        Contact testContact1 = new Contact(FirstName = 'John', LastName = 'Doe', AccountId = testAccount1.Id);
        insert testContact1;

        Account testAccount2 = new Account(Name = 'Test Account 2');
        insert testAccount2;

        Contact testContact2 = new Contact(FirstName = 'Jane', LastName = 'Smith', AccountId = testAccount2.Id);
        insert testContact2;
        
        List accountsToDeleteContacts = new List{testAccount1, testAccount2};
        List contactList = new List{testContact1, testContact2};
        System.Test.startTest();
        PracticeAccount.deleteRelatedContacts(accountsToDeleteContacts);
        System.Test.stopTest();
        
        List remainingContacts = [SELECT Id FROM Contact WHERE Id IN :contactList];
        System.assertEquals(0, remainingContacts.size(), 'Related Contacts should be deleted');
    }
}
        
    

When a case is inserted on any account put the latest case number on the account in latest case inserted field

Posted on TimeJune 19, 2024
    
        
trigger CaseTrigger on Case (after insert) {
    if(trigger.isAfter && trigger.isInsert) {
        CaseTriggerHandler.updateLatestCaseOnAccount(trigger.new);
    }
}
        
    
    
        
public class CaseTriggerHandler {

    public static void updateLatestCaseOnAccount(List newCases) {
        
        Set accIds = new Set();
        Map accMap = new Map();
        
        for(Case cs: newCases) {
            if(cs.AccountId != null) {
            	accIds.add(cs.AccountId);   
            }
        }
        
        if(!accIds.isEmpty()) {
            accMap = New Map([SELECT Id, Latest_Case_Inserted__c FROM Account WHERE Id IN:accIds]);
        }

        for(Case cs : newCases) {
            if(cs.AccountId != null && accMap.containsKey(cs.AccountId)) {
                Account a = accMap.get(cs.AccountId);
                a.Latest_Case_Inserted__c = cs.CaseNumber;
            }
        }
        
        if(!accMap.isEmpty()) {
        	update accMap.values();            
        }
    }
}        
        
    
    
        
@isTest
private class CaseTriggerHandlerTest {

    @isTest
    static void testUpdateLatestCaseOnAccount() {
        // Create test data
        Account acc = new Account(Name = 'Test Account');
        insert acc;

        Case cs = new Case(
            AccountId = acc.Id,
            Subject = 'Test Case',
            Contact_Email__c = 'test@test.com'
        );
        insert cs;

        PracticeCaseTriggerHandler.updateLatestCaseOnAccount(new List{ cs });

        Account updatedAccount = [SELECT Id, Latest_Case_Inserted__c FROM Account WHERE Id = :acc.Id];

        System.assertEquals(cs.CaseNumber, updatedAccount.Latest_Case_Inserted__c,
                            'Latest_Case_Inserted__c field on Account should be updated correctly');

    }
}        
        
    

Whenever account's phone field is updated then all related contact's phone field should also get updated with the parent account's phone

    
        
trigger AccountTrigger on Account (after update) {
    if (Trigger.isAfter && Trigger.isUpdate) {
        UpdateContactPhoneHandler.handleUpdate(Trigger.newMap, Trigger.oldMap);
    }
}
        
    
    
        
public class AccountTriggerHandler {
	public static void updatePhoneField(Map newAccMap, Map oldAccMap) {
        
      	set accIds = new Set();
        List contactToBeUpdate = new List();
        
        for(Account acc: newAccMap.values()) {
            if(acc.Phone != oldAccMap.get(acc.Id).Phone) {
                accIds.add(acc.Id);
            }
        }
        
        if (!accIds.isEmpty()) {
            List conList = [SELECT Id, Phone, AccountId 
                                     FROM Contact 
                                     WHERE AccountId IN: accIds];
            
            if(!conList.isEmpty()) {
                for(Contact con: conList) {
                    con.Phone =  newAccMap.get(con.AccountId).Phone;
                    contactToBeUpdate.add(con);
                }   
            }
        }
        
        if(!contactToBeUpdate.isEmpty()) {
            update contactToBeUpdate;
        }
    }
}        
        
    
    
        
@isTest
private class AccountTriggerHandlerTest {
    @isTest
    static void testContactPhoneUpdate() {
        // Create test data
        Account acc = new Account(Name = 'Test Account', Phone = '123-456-7890');
        insert acc;
        
        Contact con = new Contact(FirstName = 'Test', LastName = 'Contact', AccountId = acc.Id);
        insert con;
        
        // Update the Account's phone number
        acc.Phone = '987-654-3210';
        update acc;
        
        // Retrieve the updated contact
        Contact updatedCon = [SELECT Id, Phone FROM Contact WHERE Id = :con.Id];
        
        // Assert that the contact's phone field got updated
        System.assertEquals(acc.Phone, updatedCon.Phone);
    }
}        
        
    

Write a trigger that prevents records from being deleted if a certain condition is met

Posted on TimeJune 18, 2024
    
        
trigger OppTrigger on Opportunity (before delete) {
    OppTriggerHandler.handleBeforeDelete(Trigger.old);
}
        
    
    
        
public class OppTriggerHandler {
    
    public static void handleBeforeDelete(List opportunities) {
        // Check if Opportunity Stage is 'Closed Won' and prevent deletion
        for (Opportunity opp : opportunities) {
            if (opp.StageName == 'Closed Won') {
                opp.addError('Opportunity cannot be deleted because Stage is Closed Won.');
            }
        }
    }
}        
        
    
    
        
@isTest
private class OppTriggerTest {
    
    static testMethod void testPreventOpportunityDeletion() {
        // Create test opportunities
        Opportunity opp1 = new Opportunity(
            Name = 'Test Opp 1',
            StageName = 'Prospecting',
            CloseDate = Date.today() + 30
        );
        Opportunity opp2 = new Opportunity(
            Name = 'Test Opp 2',
            StageName = 'Closed Won',
            CloseDate = Date.today() + 15
        );
        
        insert new List{opp1, opp2};
        
        System.Test.startTest();
        
        // Attempt to delete records
        try {
            delete new List{opp1, opp2};
        } catch (DmlException e) {
            String expectedMessage = 'Opportunity cannot be deleted because Stage is Closed Won.';
            System.assertEquals(expectedMessage, e.getDmlMessage(0));
        }
        
        System.Test.stopTest();
    }
}
        
    

Write a trigger that creates a related record (e.g., use Account & Contact Objects) after a new record is inserted

Posted on TimeJune 17, 2024

Let's take Account and Contact object.

    
        
trigger AccountTrigger on Account (after insert) {
    if (Trigger.isInsert && Trigger.isAfter) {
        AccountTriggerHandler.createContacts(Trigger.new);
    }
}
        
    
    

public class AccountTriggerHandler {
	public static void createContacts(List newAccounts) {
		List contactsToCreate = new List();
		
		for (Account acc : newAccounts) {
			Contact newContact = new Contact(
				FirstName = 'First Name',
				LastName = 'Last Name',
				AccountId = acc.Id
			);
			contactsToCreate.add(newContact);
		}
		
		if (!contactsToCreate.isEmpty()) {
			insert contactsToCreate;
		}
	}
}

    
    

@isTest
public class AccountTriggerHandlerTest {
	
	@isTest
	static void testCreateContactAfterAccountInsert() {
		// Test scenario where a single Account is inserted
		
		System.Test.startTest();
		Account acc = new Account(Name = 'Test Account');
		insert acc;
		System.Test.stopTest();
		
		Contact createdContact = [SELECT Id, FirstName, LastName, AccountId FROM Contact WHERE AccountId = :acc.Id LIMIT 1];
		
		// Verify that a Contact was created and is associated with the Account
		System.assertNotEquals(null, createdContact, 'Contact should be created');
		System.assertEquals('First Name', createdContact.FirstName, 'First Name should be default');
		System.assertEquals('Last Name', createdContact.LastName, 'Last Name should be default');
		System.assertEquals(acc.Id, createdContact.AccountId, 'Contact should be related to the Account');
	}

	@isTest
	static void testCreateContactsForMultipleAccounts() {
		// Test scenario where multiple Accounts are inserted
		
		System.Test.startTest();
		List accounts = new List();
		for (Integer i = 0; i < 3; i++) {
			accounts.add(new Account(Name = 'Test Account ' + i));
		}
		insert accounts;
		System.Test.stopTest();

		List createdContacts = [SELECT Id, FirstName, LastName, AccountId FROM Contact WHERE AccountId IN :accounts];
		
		// Verify that a Contact was created for each Account
		System.assertEquals(3, createdContacts.size(), 'There should be 3 Contacts created');

		for (Account acc : accounts) {
			Boolean contactExists = false;
			for (Contact con : createdContacts) {
				if (con.AccountId == acc.Id) {
					contactExists = true;
					break;
				}
			}
			System.assertEquals(true, contactExists, 'A Contact should be created for each Account');
		}
	}
}

    

Write a trigger that sets a default value for a field when a new record is inserted.

Posted on TimeJune 12, 2024

Trigger