Table of Contents
Introduction to scenario
โ Apex Trigger Scenario 7
Develop an Apex Trigger so that when an opportunity is created and the account is blank, create a task under Opportunity. Hint: – AccountId == null
- Subject – Opportunity is created without Account
- Description – Opportunity is created without Account, Please assign the Correct account to Opportunity.
- Due Date – Todays Date + 7
- Status – Not Started
- Priority – High
- Related To (What) – Opportunity Id
- Assigned To (OwnerId) – Opportunity Owner Id
Hands on
trigger OpportunityTrigger on Opportunity (after insert) {
OpportunityTriggerDispatcher.dispatch(Trigger.OperationType);
}
Dispatcher Class
public class OpportunityTriggerDispatcher {
public Static void dispatch(System.TriggerOperation operationType){
switch on operationType{
WHEN AFTER_INSERT{
OpportunityTriggerHandler.afterInsert((Map)trigger.newMap);
}
}
}
}
Handler Class
public with Sharing class OpportunityTriggerHandler {
public Static void afterInsert(ListopportunityList){
List taskInsertList = new List();
for(Opportunity opp : opportunityList){
if(opp.AccountId == Null){
Task t = new Task();
t.Subject = 'Opportunity is created without Account';
t.Description = ' Opportunity is created without Account, Please assign the Correct account to Opportunity.';
t.ActivityDate = System.today().addDays(7);
t.Status = 'Not Started';
t.Priority = 'High';
t.WhatId = opp.Id;
t.OwnerId = opp.OwnerId;
taskInsertList.add(t);
}
}
try{ // Catch the error in logger Class
insert as user taskInsertList;
}
catch(System.DmlException ex){
List seList = new List();
System_Event__c se = LoggerClass.logError('OpportunityTriggerHandler',ex.getStackTraceString(),ex.getTypeName(),ex.getLineNumber());
seList.add(se);
insert seList;
}
}
}
Logger Class
// Logger Class to catch the Error
public class LoggerClass {
public Static System_Event__c logError(String className, String completeTracing, String exceptionType, Integer lineNumber){
System_Event__c se = new System_Event__c();
se.Class_Name__c = className;
se.Complete_Trace__c = completeTracing;
se.Exception_Type__c = exceptionType;
se.Line_Number__c = lineNumber;
se.User__c = UserInfo.getUserId();
return se;
}
}