You need to sign in to do that
Don't have an account?

Need help with Opportunity Trigger
I am trying to set up a trigger. Opportunity has Opportunity Products which are just Products with a relationship to an opportunity. When a custom field on Product is set a certain way I would like to update a custom field on the opportunity record to say the Product name. I am having trouble figuring out where to place the trigger and how to write the handler class.
Can you expalin why the trigger needs to be placed on Product? It seems to me that the trigger needs to be on Opportunity-Product (OpportunityLineItem) Since thats whats being created or updated when you add a product to an opportunity.
Otherwise this is the code I have now... It compiles fine but nothing happens when I expect the trigger to fire...
public with sharing class OpportunityModelNameTriggerHandler {
public void OnAfterInsert(List<OpportunityLineItem> newRecords){
updateOpportunity(newRecords);
}
public void OnAfterUpdate(List<OpportunityLineItem> oldRecords,
List<OpportunityLineItem> updatedRecords, Map<ID, OpportunityLineItem> oldMap,
Map<ID, OpportunityLineItem> newMap){
updateOpportunity(updatedRecords);
}
private void updateOpportunity(List<OpportunityLineItem> newRecords) {
Map<ID,String> productNames = new Map<ID,String>();
List<Opportunity> opps;
List<Product2> prods;
Map<ID,Opportunity> opportunities = new Map<ID,Opportunity>();
Map<ID,PriceBookEntry> pbIDs = new Map<ID,PriceBookEntry>();
Map<ID,Product2> products = new Map<ID,Product2>();
for (OpportunityLineItem oli : newRecords) {
opportunities.put(oli.id,oli.Opportunity);
pbIDs.put(oli.id,oli.pricebookentry);
}
prods = [select id from Product2 where id IN :pbIDs.keyset()];
for(Product2 prod : prods)
{
if(prod.Option_Category__c == 'Model')
productNames.put(prod.id,prod.name);
}
opps = [select id from Opportunity
where id IN :opportunities.keyset()];
for (Opportunity opp : opps)
{
opp.model__c = productNames.get(opp.id);
}
// commit the records
update opps;
}
}
PS... is there anyway I can debug this in the browser? Break points or at least print statements? Current value of variables during runtime?
bump?edit with solution
Set<Id> CurrentOppId = new Set<Id>();
for (OpportunityLineItem OppLnItem : newRecords){
CurrentOppId.add(OppLnItem.OpportunityId);
}
// Create List of One Opportunity Id to Update
List<Opportunity> OppId =
[Select o.Id from Opportunity o
where o.Id in: CurrentOppId];
List<OpportunityLineItem> relatedOLIs =
[Select oli.Id, PricebookEntry.Product2.name, PricebookEntry.Product2.Option_Category__c from OpportunityLineItem oli
where oli.OpportunityId in: CurrentOppId];
for (Opportunity opp2 : OppId){
for (OpportunityLineItem oli : relatedOLIs){
if(oli.PricebookEntry.Product2.Option_Category__c == 'Model')
{
opp2.model__c = oli.PricebookEntry.Product2.name;
}
}
}
update OppID;
}