write to get a trigger,When an opporatunity created, create a task to followup, once the task status changes to completed then update the parent opprortunity to closed won
trigger OpportunityTrigger on Opportunity (after insert, after update) {
// List to hold follow-up tasks to be created
List<Task> followUpTasks = new List<Task>();
// Map to store task Ids and their corresponding Opportunity Ids
Map<Id, Id> taskToOpportunityMap = new Map<Id, Id>();
// Check if the trigger is fired after an opportunity is created
if (Trigger.isAfter && Trigger.isInsert) {
for (Opportunity opp : Trigger.new) {
// Create a follow-up task for each new opportunity
Task followUpTask = new Task(
Subject = 'Follow-Up on Opportunity: ' + opp.Name,
Description = 'Follow up on the opportunity with an expected close date of ' + opp.CloseDate,
WhatId = opp.Id,
Status = 'Not Started',
Priority = 'Normal'
);
followUpTasks.add(followUpTask);
taskToOpportunityMap.put(followUpTask.Id, opp.Id);
}
// Insert the follow-up tasks
insert followUpTasks;
}
// Check if the trigger is fired after a task is updated
if (Trigger.isAfter && Trigger.isUpdate) {
for (Task task : Trigger.new) {
Task oldTask = Trigger.oldMap.get(task.Id);
// Check if the task status is changed from 'Not Started' to 'Completed'
if (task.Status == 'Completed' && oldTask.Status != 'Completed') {
// Update the parent opportunity status to 'Closed Won'
Id parentOpportunityId = taskToOpportunityMap.get(task.Id);
Opportunity parentOpportunity = new Opportunity(
Id = parentOpportunityId,
StageName = 'Closed Won'
);
update parentOpportunity;
}
}
}
}
This trigger fires after the insert and after the update events of an Opportunity and Task objects. When an Opportunity is inserted, the trigger creates a follow-up Task associated with the Opportunity. When a Task's status is changed to 'Completed,' the trigger finds the parent Opportunity and updates its StageName to 'Closed Won.
Please try with the below trigger :
This trigger fires after the insert and after the update events of an Opportunity and Task objects. When an Opportunity is inserted, the trigger creates a follow-up Task associated with the Opportunity. When a Task's status is changed to 'Completed,' the trigger finds the parent Opportunity and updates its StageName to 'Closed Won.
Hope this helps !
Thank you.