function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
phiberoptikphiberoptik 

Trigger should only fire when Task is completed - what am I missing?

trigger TaskRelatedToOpp on Task (before insert, before update) {

// Goal: Find the opp Stage of the opportunity that a task is related to
// and update the Opportunity_Stage__c field on the task object with the value

// If related to an Opportunity, query to find out the Opportunity number

// Create collection of tasks that are related to an opp (where the opp is listed only once)
    Set<Id> opIds = new Set<Id>();
    for(Task t : trigger.new){
        String wId = t.WhatId;
        if(wId!=null && wId.startsWith('006') && !opIds.contains(t.WhatId)){
            opIds.add(t.WhatId);
        }
    }
    // Pull in opp ids and related field to populate task record
    List<Opportunity> taskOps = [Select Id, StageName from Opportunity where Id in :opIds];
    Map<Id, Opportunity> opMap = new Map<Id, Opportunity>();
    for(Opportunity o : taskOps){
        opMap.put(o.Id,o);
    }
    // Update custom task field with custom opp field
    for(Task t : trigger.new){
        String wId = t.WhatId;
        if(wId!=null && wId.startswith('006')){
            Opportunity thisOp = opMap.get(t.WhatId);
            if(thisOp!=null){t.Opportunity_Stage__c = thisOp.StageName;} 
        }
    }
}

 

I just need this to populate the Opportunity_Stage__c field only when the Status is Completed. Thanks.

Best Answer chosen by Admin (Salesforce Developers) 
phiberoptikphiberoptik

I guess I have to answer my own questions around here...

 

trigger TaskRelatedToOpp on Task (before insert, before update) {

// Goal: Find the opp Stage of the opportunity that a task is related to
// and update the Opportunity_Stage__c field on the task object with the value

// If related to an Opportunity, query to find out the Opportunity number

// Create collection of tasks that are related to an opp (where the opp is listed only once)
    Set<Id> opIds = new Set<Id>();
    for(Task t : trigger.new){
        String wId = t.WhatId;
        if(wId!=null && wId.startsWith('006') && !opIds.contains(t.WhatId)){
            opIds.add(t.WhatId);
        }
    }
    // Pull in opp ids and Stage field to populate task record
    List<Opportunity> taskOps = [Select Id, StageName from Opportunity where Id in :opIds];
    Map<Id, Opportunity> opMap = new Map<Id, Opportunity>();
    for(Opportunity o : taskOps){
        opMap.put(o.Id,o);
    }
    // Update custom task field with opp Stage field
    for(Task t : trigger.new){
        String wId = t.WhatId;
        String tSt = t.Status;
        if(wId!=null && wId.startswith('006') && tSt=='Completed'){
            Opportunity thisOp = opMap.get(t.WhatId);
            if(thisOp!=null){t.Opportunity_Stage__c = thisOp.StageName;} 
        }
    }
}