1

I am trying to update Task Records and set the WhoId (a look up field) on the Task equal to the value of a lookup field on the associated (Related to) Opportunity.

I have a specific list of Opportunities that I query and store into a map, I then want to loop over the Task records in Trigger.new and based on the subject line, I want to set the "WhoId" field on the Task equal to the value of the "Main_Contact_ID__c" field in the Opportunity where the Opportunity ID is Equal to the value of the "WhatId" field on the task.

I have this code which doesn't quite work as I need it to:

 Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([SELECT Id, Main_Contact_ID__c FROM Opportunity WHERE Id = :oppIds]);

    for(Task t: Trigger.new) {
        // if the task subject contains Business-Deal
        if( t.Subject.contains('Business-Deal') ) {
            t.WhoId = oppMap.get('Main_Contact_ID__c');

        }

    }
2

Maps work as a key-value type thing. They take a given key, and associate it to a single value (the "value" part of the map can itself be a collection, but let's keep it simple here).

What you have here is a Map<Id, Opportunity>. The key is the Opportunity Id, and the value is the entire Opportunity record.

In this case, the thing you're getting back from the map is an SObject (an Opportunity, to be more specific), and you access the individual fields using dot-notation like you would with any other object.

The other part of this is that you need to get an Id from your Task (that hopefully points to an Opportunity, and there are several methods to check that which are beyond the scope of your question). Unless you're using a custom field, that's probably the WhatId field on the Task.

You could do all of this on a single line, but to illustrate my points, I'll keep it on multiple lines. The gist of it is that you want to do something like

// Get the Opportunity from your map
Opportunity relatedOpp = oppsMap.get(myTask.whatId);

// You should consider doing a null check before this next line of code
// If you don't, you're setting yourself up to get some Null Pointer Exceptions
myTask.Field__c = relatedOpp.Opp_Field__c;

Again, you use the map key to get the corresponding value, and since your value is an SObject, you access fields like you would with any other SObject variable (using dot notation).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.