reeeval
10/10/2016 - 8:37 AM

Apex trigger for creating Task automatically when stage has been changed from Opportunity

Apex trigger for creating Task automatically when stage has been changed from Opportunity

trigger autoCreateTaskWhenStageChanged on Opportunity (before insert, before update) {
    List<Task> tasks = new List<Task>();
    
    for (Opportunity opp : Trigger.new) {
        Id managerId = [SELECT Id, ManagerId FROM User WHERE Id = :opp.OwnerId].ManagerId;
        
        if (Trigger.newMap.get(opp.Id).Stage_Seq__c == 1) {
            Task newTask1 = new Task();
            newTask1.subject = 'Automated Task 1 - Stage 1';
            newTask1.whatId = opp.Id;
            newTask1.ownerId = opp.OwnerId;
            newTask1.status = 'In Progress';
            newTask1.Priority = 'Normal';
            tasks.add(newTask1);
            
            Task newTask2 = new Task();
            newTask2.subject = 'Automated Task 2 - Stage 1';
            newTask2.whatId = opp.Id;
            newTask2.ownerId = managerId != null ? managerId : opp.OwnerId;
            newTask2.status = 'In Progress';
            newTask2.Priority = 'Normal';
            tasks.add(newTask2);
        }
        else if (Trigger.newMap.get(opp.Id).Stage_Seq__c == 2) {
            Task newTask1 = new Task();
            newTask1.subject = 'Automated Task 1 - Stage 2';
            newTask1.whatId = opp.Id;
            newTask1.ownerId = opp.OwnerId;
            newTask1.status = 'In Progress';
            newTask1.Priority = 'Normal';
            tasks.add(newTask1);
        }
        else if (Trigger.newMap.get(opp.Id).Stage_Seq__c == 2) {
            Task newTask1 = new Task();
            newTask1.subject = 'Automated Task 1 - Stage 3';
            newTask1.whatId = opp.Id;
            newTask1.ownerId = opp.OwnerId;
            newTask1.status = 'In Progress';
            newTask1.Priority = 'Normal';
            tasks.add(newTask1);
        }
        else if (Trigger.newMap.get(opp.Id).Stage_Seq__c == 10) {
            Task newTask1 = new Task();
            newTask1.subject = 'Automated Task 1 - Stage 10';
            newTask1.whatId = opp.Id;
            newTask1.ownerId = opp.OwnerId;
            newTask1.status = 'In Progress';
            newTask1.Priority = 'Normal';
            tasks.add(newTask1);
        }
    }
    
    if (tasks.size() > 0) {
        insert tasks;
    }
}