+ Start a Discussion
Alex DornAlex Dorn 

Lead code work for opportunity as well

After working with some people on here I was able to get a code that made it so the last activity's subject was placed in a Last_Activity_Subject__C field. I would like to make this same code for our opportunities. All I did to alter the code was replace any instance of Lead with Opportunity, and there was no errors saving, but the code does not work. Can anyone provide insight on what else I have to change. Here is the code:

trigger updateRelatedOpportunity on Task (after insert,after update) {

List<Id> OpportunityIds = new List<Id>();
List<Opportunity> OpportunityList = new List<Opportunity>();

for(Task t :trigger.new)
    {
    if(t.whoId!=null)
    {
        Schema.SObjectType tType= t.whoId.getSObjectType();
        if(tType == Opportunity.Schema.SObjectType)
        {
            OpportunityIds.add(t.WhoId);
        }
    }
    }
    {
    //Querying the related Opportunity based on whoId on Task
    Map<Id,Opportunity> OpportunityMap =  new Map<Id,Opportunity>([select id,Last_Activity_Subject__C from Opportunity where id in:OpportunityIds]);
    
    for(Task t :Trigger.new)

        for(Opportunity l : OpportunityMap.Values())
        {
            l.Last_Activity_Subject__C = t.subject;
            OpportunityList.add(l);
        }
    }
    // updating the Opportunity
    if(OpportunityList.size()>0)
    {
        update OpportunityList;
    }
}
Best Answer chosen by Alex Dorn
ShashForceShashForce
Hi Alex,

Here's one more difference between Leads and Opportunities. Leads are stored as "WhoId" on Tasks, but Opportunities are stored as "WhatId". Please chance all the occurances of "WhoId" in your code to "WhatId", and you should be good.

If this answers your question, please mark this as the Best Answer for this post, so that others can benefit from this post.

Thanks,
Shashank

All Answers

ShashForceShashForce
Hi Alex,

Here's one more difference between Leads and Opportunities. Leads are stored as "WhoId" on Tasks, but Opportunities are stored as "WhatId". Please chance all the occurances of "WhoId" in your code to "WhatId", and you should be good.

If this answers your question, please mark this as the Best Answer for this post, so that others can benefit from this post.

Thanks,
Shashank
This was selected as the best answer
Alex DornAlex Dorn
That worked perfectly thank you Shashank, but when I tried deploying to the production version it fails do you know why that would be? I get this error:
updateRelatedLead               Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required
updateRelatedOpportunity    Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required
Deploy Error                             Average test coverage across all Apex Classes and Triggers is 0%, at least 75% test coverage is
And I am including the new fields in the deployment.