+ Start a Discussion
Eric_SalesForceEric_SalesForce 

Apex Trigger cannot handle batch operations on recurring tasks

Hello,

 

Basically what I am trying to do is make it so when an opportunity is transfered to a different owner, the associated tasks with that opportunity are also transfered to the new owner. The problem I have is I get a list of the opportunities to transfer, then for each of those opportunities I get a list of the tasks and then I try to move everything over. However I get this error and I am not sure how to handle the error outside of the outer loop.

 

For(All Opportunities to Update Owner)

{

    For(All Tasks of Opporunitiy)

          Change Owner)

{

GlynAGlynA

Eric,

 

Here's something that should do the trick:

 

trigger OpportunityAfterTrigger on Opportunity ( after update )
{
    Set<Id> set_TransferredOpportunities = new Set<Id>();

    for ( Opportunity theOpportunity : Trigger.new )
    {
        Opportunity oldOpportunity = Trigger.oldMap.get( theOpportunity.Id  );

        if ( theOpportunity.OwnerId != oldOpportunity.OwnerId )
        {
            set_TransferredOpportunities.add( theOpportunity.Id );
        }
    }
    if ( set_TransferredOpportunities.isEmpty() ) return;

    List<Task> list_TasksToTransfer =
    [   SELECT  OwnerId
        FROM    Task
        WHERE   WhatId IN :set_TransferredOpportunities
    ];

    for ( Task aTask : list_TasksToTransfer )
    {
        aTask.OwnerId = Trigger.newMap.get( aTask.WhatId ).OwnerId;
    }
    update list_TasksToTransfer;
}

The first half of the code creates a set of IDs of any Opportunities whose Owner has changed.  If there aren't any, the trigger is done.

 

Otherwise, it queries all of the Tasks related to the transferred Opportunities.  Then, it iterates over these and changes their Owner to match that of the related Opportunity.  Finally, it updates the Tasks to commit the changes to the database.

 

Let me know if this works, or if you have any questions about it.  Good luck with your project.

 

If this helps, please mark it as a solution, and give kudos (click on the star) if you think I deserve them. Thanks!

 

-Glyn Anderson
Certified Salesforce Developer | Certified Salesforce Administrator