Scenario:
Custom Convert button on Opportunity that creates a Project (custom object that can have multiple Opportunities associated to it) that the Opportunity is associated to via lookup field on Opportunity. Once the Project has been created I want to update the Project__c lookup on the originating Opportunity with the Project Id.
I sort of have this working by using custom button with URL encoding which passes the originating Opportunity Id to the Opportunity_Id__c field in the edit page on the soon to be created Project. Once the Project is inserted I then have a trigger that uses the Opportunity Id values stored on the Project to update the Project__c lookup on the relevant Opportunities.
Here's the button URL:
/a0B/e?retURL=/{!Opportunity.Id}&Name={!Opportunity.Name}&00N3C000000Hekv=
{!Opportunity.Amount_As_Numeric__c}&CF00N5000000A3T6Y=
{!Opportunity.Account}&00N3C000000Hn4y={!Opportunity.Id}
Here's the service class associated with the after insert trigger on the newly created Project:
public with sharing class ProjectService {
public static void associateConvertedOpportunityToNewlyCreatedProject(List<Project__c> newList){
Map<Id,Id> opptyProjMap = new Map<Id, Id>();
List<Id> updateOpptyIds = new List<Id>();
List<Opportunity> updateOpptys = new List<Opportunity>();
for(Project__c p: newList){
Id opptyId = Id.valueOf(p.Opportunity_Id__c);
opptyProjMap.put(opptyId, p.Id);
updateOpptyIds.add(opptyId);
System.debug('opptyProjMap: ' + opptyProjMap);
System.debug('updateOpptyIds: ' + updateOpptyIds);
}
if (!opptyProjMap.isEmpty()) {
for (Opportunity o : [select Id, Design_Atelier_Project__c from Opportunity where Id in :updateOpptyIds]) {
if (opptyProjMap.containsKey(o.Id)) {
o.Design_Atelier_Project__c = opptyProjMap.get(o.Id);
updateOpptys.add(o);
}
}
}
System.debug('updateOpptys: ' + updateOpptys);
Utility.logUpdate(updateOpptys);
}
}
This works, but it forces me to have the Opportunity_Id__c field visible on the edit screen of the new soon to be created Project. I'm guessing I could probably do this in a more elegant fashion but its 3am and my brain is fried. Any guidance would be much appreciated.
Good night and thanks!