Code:
trigger Attempt1 on OpportunityLineItem (after insert)
{
List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
List<String> lstProductNames = new List<String>();
//create a list where all the products to be added.
for(OpportunityLineItem optLineItem: Trigger.new)
{
if(optLineItem.Name == 'Product A')
{
lstProductNames.add(optLineItem.Name);
lstProductNames.add('Product B');
}
}
//retrieve the values based on Product list
List<OpportunityLineItem> lstOpptyLineItems = [SELECT OpportunityId, Name , PricebookEntryId, Quantity, UnitPrice
FROM OpportunityLineItem
WHERE Id = :Trigger.new
AND Name IN:lstProductNames];
//create a map which contains Product Name and OpportunityLineItem
Map<String, OpportunityLineItem> mapOpptyLineItem = new Map<String, OpportunityLineItem>();
for(OpportunityLineItem item:lstOpptyLineItems)
{
mapOpptyLineItem.put(item.Name, item);
}
for(OpportunityLineItem item: lstOpptyLineItems)
{
//retrieve the values and compare the name
if(item.name == 'Product B')
{
//retrieve Product A item from the map.
OpportunityLineItem itemProductA = mapOpptyLineItem.get('Product A');
//now assign Product A items as required, you can retrieve the amount from Product A
oliList.add(new OpportunityLineItem(
OpportunityId = itemProductA.OpportunityId,
PricebookEntryId = itemProductA.PricebookEntryId,
Quantity = 1,
UnitPrice = 25)
);
}
}
insert oliList;
}
The goal of the trigger is to automatically add "Product B" to the opportunity once "Product A" has been added manually by the Technical Writer. Also, the $ value of "Product B" needs to be 5% of "Product A". To add to this complex situation, we have two pricebooks. One is named "Standard Price Book" and the other is named "TD Pricebook". Both pricebooks have "Product A" and "Product B"...
Here is the data:
Standard Price Book (pricebook2id: 01sA00000004lbRIA1)
- Product A (full price book entry id: 01uA000000QPDlTI1a)
- Product B (full price book entry id: 01uA000000QPDldI1b)
TD Pricebook (pricebook2id: 01sA00000007eyNIA2)
Product A (full price book entry id: 01uA000000QPDlTI2a)
Product B (full price book entry id: 01uA000000QPDldI2b)