0
    trigger OpportunityTrigger on Opportunity(after update) {
    List<Id> newOwnerOpps = new List<Id>();
    for (Opportunity opp : Trigger.New) {
        if (opp.OwnerId != Trigger.Oldmap.get(opp.Id).OwnerId) {
            newOwnerOpps.add(opp.Id);
        }
    }
    List<Task> restoreTaskOwner = new List<Task>();
    if (!newOwnerOpps.IsEmpty()) {
        for (Task tsk : [SELECT Id, OwnerId, WhatId FROM Task WHERE WhatId IN :newOwnerOpps AND IsClosed = false]) {
            if (tsk.OwnerId == Trigger.Oldmap.get(tsk.WhatId).OwnerId) {
                tsk.OwnerId = Trigger.Oldmap.get(tsk.WhatId).OwnerId;
                restoreTaskOwner.add(tsk);
            }
        }
        if (!restoreTaskOwner.isEmpty()) {
            update restoreTaskOwner;
        }
    }
}

Old Owner = User A, New Owner User B

  1. User A creates a task for User A, when owner changes task still assigned to User A
  2. User A creates a task for User B, when owner changes, task still assigned to User B
  3. User C creates a task for User A, when owner changes task is still assigned to User A
  4. User C creates a task for User D, when owner changes task is still assigned to User D basically, task owner NEVER changes on ownership change

Currently, this works for scenarios 1, 2, and 4, but not scenario 3.

What is wrong with my trigger?

3
  • As written, it looks to me like the trigger will not work for any of the scenarios (except 2, which should require no action), because that if condition is tautological - it's checking for X and then doing an assignment X. Is that a typo in the post?
    – David Reed
    Apr 2 '21 at 14:58
  • Is there a way to correct my opportunity trigger to fit all four scenarios without also creating a task trigger?
    – Jree
    Apr 2 '21 at 16:34
  • I'm happy to post an answer (it looks to me like you just need to change == to !=), but I'm trying to square what I'm seeing with your description since it doesn't look to me like it should work at all right now.
    – David Reed
    Apr 2 '21 at 16:54
0

As shown here, the trigger shouldn't work for any of the scenarios (except Scenario 2, which if I understand correctly is the OOTB behavior) due to what I think is just a typo:

if (tsk.OwnerId == Trigger.Oldmap.get(tsk.WhatId).OwnerId) {
    tsk.OwnerId = Trigger.Oldmap.get(tsk.WhatId).OwnerId;

The if condition should be !=.

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.