Here's something that I'm trying to do which I feel as though I've made it 75% of the way through. Right now let's assume I have the ability to generate an opportunity when a certain action is performed on an Activity, and then populate a regular text field on the Opportunity (before Insert) that stores the ActivityId (not a lookup) on ActivityId__c.
What I'm trying to do is use that Id (Event or Task) to find the Activity that created the opportunity, and change the WhatId to be the new opportunity. The Activity's original WhatId will be looking up to the Account. Here's what I've done so far:
trigger activityCreatesOpp on Opportunity (after insert) {
// creates lists to store the IDs of Events and Tasks
List<Id> EventIds = New List<Id>();
List<Id> TaskIds = New List<Id>();
for(Opportunity opp : Trigger.new) {
// checks to see if the Opportunity has ActivityId__c set to an event, and if so adds that EventId to the EventIds list
String ActivityId = opp.ActivityId__c;
if(opp.ActivityId__c != null && ActivityId.startsWith('00U')){
EventIds.add(opp.ActivityId__c);
}
// checks to see if the Opportunity has Activity Id set to a task, and if so adds that TaskId to the TaskIds list
if(opp.ActivityId__c != null && ActivityId.startsWith('00T'){
TaskIds.add(opp.ActivityId__c);
}
}
// if there is an Event Id found in the ActivityId field on the Opportunity, set the WhatId to that of the Opportunity
if(EventIds.size() > 0){
List<Event> eventList = [SELECT Id, WhatId FROM Event WHERE Id in :EventIds];
for(integer i = 0 ; i < eventList.size(); i++){
eventList[i].WhatId = ???
}
}
// if there is a Task Id found in the ActivityId field on the Opportunity, set the WhatId to that of the Opportunity
if(TaskIds.size() > 0){
List<Task> taskList = [SELECT Id, WhatId FROM Task WHERE Id in :TaskIds];
for(integer i = 0 ; i < taskList.size(); i++){
taskList[i].WhatId = ???
}
}
}
My main issue is trying to figure out how to get the OpportunityId into the WhatId (as you can see). A couple thoughts I had was that perhaps I should also create a list of the OpportunityId when I loop through the opps, and then use that list to populate the WhatId. However, I get the sense that I won't be able to ensure it's the right Id.
My other idea (which I think is probably the better solution) is to use Maps and to map the Opportunity Id to the Event/Task Id. This makes a lot of intuitive sense to me because that is that's the reality of the situation: I need to relate a specific Opportunity to a specific Activity.
Am I on the right track here? Appreciate any help as well as any suggestions/observations regarding my code as a whole.
Thanks!