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 

Trying to populate the Opportunity Stage in a custom field on the Task object

I know for Apex code, this is a pretty straight forward trigger, but not having any dev experience, I am not clear on how to achieve this.

 

I have a custom text field on activities called Opportunity Stage (Opportunity_Stage__c). I want this field populated with the current Stage (after insert) of the Opportunity that the task is associated with.


Any help is appreciated!

Best Answer chosen by Admin (Salesforce Developers) 
phiberoptikphiberoptik

Disregard... I figured it out:

 

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;} 
        }
    }
}