Can I get help with a trigger that will populate the opportunity stage on a related task? I'm very green with triggers so you cannot get to basic if you feel so inclined.

Thanks for the help.

  • Jim, let's walk through this so you start at least thinking along the right lines... Spell out in a sentence exactly what you are after (this always helps you think out where/when things should happen). "Before/after x is done (inserted/updated), I want y to happen..." Apr 22, 2014 at 14:57

3 Answers 3


If you navigate to "Customize" in the setup menu, and then "Activities" and finall "Task Triggers" you will be taken to your task trigger page. Chances are you will want to click "New" here. This will take you to a new task trigger page with a skeleton of:

new trigger

You will want to populate it up to be something along the lines of:

trigger atrigger on Task (before insert, before update)
    // Prepare a list of the parent opportunities and load into a map
    List<Id> theParents = new List<Id>();
    for(Task thisTask : trigger.new)

    Map<Id, Opportunity> theOpps = new Map<Id,Opportunity>([SELECT Id, StageName FROM Opportunity WHERE Id IN :theParents]);

    // Now go through the tasks and set their stage on the child task field (by pulling the relevant parent back out the map)
    for(Task thisTask : trigger.new)
        thisTask.Parent_Stage__c = theOpps.get(thisTask.WhatId).StageName;


(Now, whilst that compiles, but I don't know the specifics of what you are trying to achieve, so expect some tweaking on your part to make this work)


I Hope below link help you!

populate the Opportunity Stage in a custom field on the Task object: https://developer.salesforce.com/forums/ForumsMain?id=906F000000091fKIAQ



Thanks for the link, that is exactly what I'm looking for! Can someone offer up suggestions for the test class?

I have the following, but I'm not sure how to fill in the blanks to make this work:

public class TestClass{

         static testMethod void Test(){
                 // Create the data that you would need here, for example in your case you would create a collection of tasks
                 List<Task> tasks = new List<Task>();

                 for(Integer i = 0; i < 50; i++){ //You can add as many test cases as you want here, typically I go for 25-100
                  <Create new tasks while giving them the required information here, you should include some sort of test indicator>
                  tasks.add(<the task you created above>)

                  insert tasks;

                  //Query the database using SOQL to get the list of tasks you just inserted and their related opportunities
                  //Using System.assertEquals(value a, value b) make sure that the opportunity stage is update correctly

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .