Okay guys, I have now spent 4 days and counting on this trigger and I really feel it shouldn't be this hard but I am having a lot of trouble trying to get it done so help would be greatly appreciated!
This is my trigger so far:
trigger ParentOppToChild on Opportunity(after update)
{
//Get all Opportunity's with stage name = to closed won
Set<Id> opportunityIds = new Set<Id>();
for(Opportunity opp : Trigger.new)
{
if(opp.StageName == 'Closed Won' && Trigger.oldMap.get(opp.Id).StageName != 'Closed Won')
{
opportunityIds.add(opp.Id);
}
}
// Get Opportunity Line Items
for (Opportunity opp : [SELECT Id, (SELECT Id FROM OpportunityLineItems) FROM Opportunity WHERE Id IN :opportunityIds])
{
// Create grouping of opp line items by Dealership
Map<Id, List<OpportunityLineItem>> mapDealershipItems = new Map<Id, List<OpportunityLineItem>>();
List<OpportunityLineItem> OppLineItemsList = new List<OpportunityLineItem>();
for (OpportunityLineItem oppLineItem : opp.OpportunityLineItems)
{
mapDealershipItems.put(OppLineItem.Dealership__c, OppLineItemsList);
If(mapDealershipItems.containsKey(oppLineItem.Dealership__c ))
{
// TO-DO Check if Dealership is a key in the map
// 1. Yes - Add opp line item to the list
// 2. No - Add dealership (key) and new list with item inside (value)
//
OppLineItemsList.add(OppLineItem);
}
else
{
OppLineItemsList.add(OppLineItem);
;
}
}
//mapDealershipItems.put(key, value)
// Create opportunity and opp line items
for (Id dealershipId : mapDealershipItems.keySet())
{
// TO-DO Create opportunity
Opportunity opportunity = new Opportunity(AccountId = dealershipId,
CloseDate = Date.today(),
StageName = 'Group Contract Signed');
try {
insert opportunity;
} catch (Exception e1) {
}
// TO-DO Create opp line items
// - Check checkbox in opportunity
List<OpportunityLineItem> oppLineItems = new List<OpportunityLineItem>();
for(OpportunityLineItem oli : opportunity.OpportunityLineItems)
{
oppLineItems.add(oli);
}
try {
insert oppLineItems;
} catch (Exception e2) {
}
}
}
}
I basically need to create a new opportunity (child record type) if the parent opportunity is 'closed won'. This new opportunity will have the account name set to the dealership__c(lookup field to account on OpportunityLineItem) and all the opportunity line items in its related list will be the ones related to the dealership (only the items that were associated with the dealer in the related list of the now 'closed won' parent opportunity).
I am having trouble grouping the Line Items with the Dealerships. And then trying to create the new opportunities and the line items related to it.
Again, I would be forever grateful to anyone who can help with this.