3

I want add a default task to an opportunity when this one is close won and the opportunity hasn't any task.

I get the error compiling the below code:

Entity 'Task' is not supported for semi join inner selects

trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
List<Task> taskList = new List<Task>();
    for (Opportunity opp : [Select Id, Name from Opportunity 
                           Where Id IN :Trigger.New AND 
                                Id NOT IN (Select WhatId from Task)]) {
    // Add a default task for this Opportunity
        If (opp.StageName == 'Closed Won') {
            taskList.add(New Task(Subject ='Follow Up Test Task',
                                  WhatId = opp.Id)); 
           }

    } //end for loop
}
4

You need to split out a separate query. As the error states, you can't use this join:

Id NOT IN (Select WhatId from Task)

One possible approach to splitting out the query:

Set<Id> opportunityIdsWithTask = new Map<Id, AggregateResult>([
    SELECT WhatId Id FROM Task
    WHERE WhatId IN :trigger.new
    GROUP BY WhatId
]).keySet();

Then just add add that as your filter instead of a join:

Id NOT IN :opportunityIdsWithTask
0

This was a solid post and ultimately helped me clean up my code.

My final code looked like this

trigger ClosedOpportunityTrigger on Opportunity(after insert, after update) {
    List<Task> taskList = new List<Task>();

    // Create a set of Opportunities with no Tasks
    Set<Id> opportunityIdsWithTask = new Map<Id, AggregateResult>([
    SELECT WhatId Id FROM Task
    WHERE WhatId IN :trigger.new
    GROUP BY WhatId
]).keySet();

    // Add an Task for each Opportunity if it doesn't already have one.
    // Iterate over Opportunities that are in this trigger but that don't have Tasks.
  for (Opportunity a : [SELECT Id,Name FROM Opportunity
                     WHERE Id IN :Trigger.New AND
                     Id NOT IN :opportunityIdsWithTask]) {

       taskList.add(new Task(Subject = 'Follow Up Test Task',
                             whatId  = a.Id));

   }


    if (taskList.size() > 0) {
        insert taskList;

   }
}

The only way I would have ever learned that tasks can't be used in inner joins is by finding this thread. I thought it was awesome because I had the same shell as OP. I added the recommended and voila!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.