I am curious what the rules are for using an update statement in a before insert trigger.
The below code is called during a before insert trigger on tasks. Basically what I am doing is saying "Hey, there is a new task associated with this opportunity. Let's check to see if there are any other open tasks associated with this opp. If there are, let's close them up"
public with sharing class NextStepDueDateTask
{
public static void handleTrigger(List<Task> newTasks) {
Set<Id> OppIds = new Set<Id>();
for(Task t: newTasks)
{
// Grab all tasks that are related to Opportunities and are Open
String s1 = t.WhatId != null ? String.valueof(t.WhatId) : '';
if(s1.startsWith('006') && t.status == 'Open')
{
OppIds.add(oppId);
}
}
List<Opportunity> Opps = [ SELECT id, (SELECT id, status from Tasks WHERE status = 'open' ) from Opportunity where id in :OppIds ];
set<Task> tasksToUpdate = new List<Task>();
for(Opportunity opp : Opps)
{
if(opp.Tasks != null)
{
for( Task t : opp.Tasks )
{
t.Status = 'Completed';
tasksToUpdate.add(t);
}
}
}
update tasksToUpdate;
}