trigger OpportunityLineItemAfterUpdateAfterInsert on OpportunityLineItem (after update, after insert) {
List<ID> oppIDList = new List<ID>();
List<String> oppFieldsList = new List<String>();
List<Opportunity> oppFieldsToUpdate = new List<Opportunity>();
Integer i = 0;
for (OpportunityLineItem oppLI : Trigger.new) {
oppIDList.add(oppLI.OpportunityId);
oppFieldsList.add(oppLI.Opportunity_Product_Field__c);
}
List<Opportunity> oppFields = [SELECT oppFieldsList FROM Opportunity WHERE Id IN: oppIDList];
for (OpportunityLineItem oppLI : Trigger.new) {
oppFieldsToUpdate.add(oppFields.put(oppFieldsList[i],oppLI.UnitPrice));
i++;
}
update oppFieldsToUpdate;
}
I think I just figure it out. This will dynamically add fields and remove fields based on an API label we pass into the pricebook as a string and then looks it up accordingly and then pastes the values back to the opportunity dynamically. I tested it a few times and it looks like it works. woo. trigger OpportunityLineItemAfterUpdateAfterInsert on OpportunityLineItem (after update, after insert) {
System.debug('Price Update 1');
List<ID> oppIDList = new List<ID>();
List<String> oppFieldsList = new List<String>();
Map<ID,Opportunity> oppFieldsToUpdate = new MAP<ID,Opportunity>();
Integer i = 0;
String soqlQueryList = '';
System.debug('Price Update 2');
for (OpportunityLineItem oppLI : Trigger.new) {
oppIDList.add(oppLI.OpportunityId);
oppFieldsList.add(oppLI.Opportunity_Product_Field__c);
}
System.debug('PriceUpdate 2.5');
set<ID> oppDeDupeIDSet = new set<ID>();
List<ID> oppIDListDeDuped = new List<ID>();
oppDeDupeIDSet.addAll(oppIDList);
oppIDListDeDuped.addAll(oppDeDupeIDSet);
System.debug('Price Update 3');
System.debug(oppFieldsList);
System.debug('3.1');
set<String> myset = new set<String>();
List<String> oppFieldsListDeDupe = new List<String>();
myset.addAll(oppFieldsList);
oppFieldsListDeDupe.addAll(myset);
System.debug('3.2');
system.debug(oppFieldsListDeDupe);
System.debug('3.3');
for (Integer p=0; p < oppFieldsListDeDupe.size()-1;p++){
soqlQueryList += oppFieldsListDeDupe[p] + ',';
}
System.debug('Price Update 3.5');
soqlQueryList += oppFieldsListDeDupe[oppFieldsListDeDupe.size()-1];
System.debug('Price Update 4');
String soqlQuery = 'Select ' + soqlQueryList + ' FROM Opportunity WHERE ID IN: oppIDListDeDuped';
System.debug('Price Update 5');
System.debug(oppIDListDeDuped.size());
List<Opportunity> oppsFields = database.query(soqlQuery);
for(Integer p=0; p< oppIDListDeDuped.size();p++){
System.debug('Price Update 6');
Opportunity opp = new Opportunity();
List<Opportunity> helperList = new List<Opportunity>();
for (OpportunityLineItem oppLI : Trigger.new) {
//Opportunity opp = new Opportunity();
opp.id = oppLI.OpportunityId;
opp.put(oppLI.Opportunity_Product_Field__c , oppLI.UnitPrice);
helperList.add(opp);
}
oppFieldsToUpdate.putAll(helperList);
}
System.debug('Price Update 7');
System.debug(oppFieldsToUpdate);
update oppFieldsToUpdate.Values();
}