Example: When Opportunity get updated. Create new Task on Primary Contact of that Opportunity.
Solution
OpportunityTrigger
trigger OpportunityTrigger on Opportunity (after update) {
OpportunityTriggerHandler handler = new OpportunityTriggerHandler();
if(trigger.isAfter && Trigger.isUpdate) {
handler.createTaskOnPrimaryContact(trigger.old);
}
}
OpportunityTriggerHandler
public class OpportunityTriggerHandler {
public void createTaskOnPrimaryContact(List<Opportunity> lstOppor) {
List<OpportunityContactRole> contactRoles = [Select Id, ContactId,OpportunityId From OpportunityContactRole Where IsPrimary = True and OpportunityId in: lstOppor];
List<Task> lstTask = new List<Task>();
for(OpportunityContactRole oppContactRole: contactRoles) {
List<Opportunity> oppr = [Select Id, OwnerId From Opportunity Where Id=: oppContactRole.OpportunityId limit 1];
Task task = new Task(Subject='Email',
ActivityDate = System.Today() + 12,
Status = 'InProgress',
OwnerId = oppr[0].OwnerId ,
WhatId = oppContactRole.OpportunityId, // Related to does not support Contact
WhoId = oppContactRole.ContactId
);
lstTask.add(task);
}
System.debug(lstTask);
insert lstTask;
}
}