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
Jim GentileJim Gentile 

Populate the Opportunity Stage in a custom field on the Task object - Need Class

Hello,

From a previous post I was able to figure out how to write a trigger for populating the opportunity stage on a related task (https://developer.salesforce.com/forums/ForumsMain?id=906F000000091fKIAQ).

My coverage for this trigger is 0% because I do not have a test class.  Can someone help me with this code?  I should emphasize that I am brand new to triggers.

Thanks in advance for the help.

Here is what my trigger looks like:

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;}
        }
    }
}
AmitAmit (Salesforce Developers) 
Hello,

Please refer following links for more information :

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_qs_test.htm

https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods http://teachmesalesforce.wordpress.com/2011/05/07/how-to-write-a-trigger-test/