function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Zoren DomingoZoren Domingo 

Update a field in opportunity after adding a particular products

Can anyone help me on these? I'm trying to update a field in opportunity after I add a products and also when I remove it.

trigger AdworksTriggerForCampaignScoreCard on Opportunity (after update) {
    
    List<OpportunityLineItem> relatedOppLI = [SELECT Id,Product2.Name FROM OpportunityLineItem
        WHERE OpportunityId IN :Trigger.New];
    
    List<Opportunity> relatedOpps = [SELECT Id,Name,Campaign_Score_Card__c FROM Opportunity];
    
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    for(OpportunityLineItem oppLI : relatedOppLI) {      
        for(Opportunity opp : relatedOpps){
            if(Trigger.isUpdate){
                if(oppLI.Product2.Name == 'Addressable')
                {          
                    opp.Campaign_Score_Card__c = true;
                    oppsToUpdate.add(opp);
                }
            }
        }
    }
    update oppsToUpdate;
}
Raj VakatiRaj Vakati
Try this code .. trigger should be on OpportunityLineItem  not on Opportunity
 
trigger AdworksTriggerForCampaignScoreCard on OpportunityLineItem (after update) {

	Set<Id> CurrentOppId = new Set<Id>();

	 for (OpportunityLineItem OppLnItem : Trigger.new){
		CurrentOppId.add(OppLnItem.OpportunityId);
}
	


List<Opportunity> relatedOpps = [SELECT Id,Name,Campaign_Score_Card__c FROM Opportunity where Id In : : CurrentOppId];

List<Opportunity> oppsToUpdate = new List<Opportunity>();

	for(Opportunity opp : relatedOpps){
		if(Trigger.isUpdate){
			if(oppLI.Product2.Name == 'Addressable')
			{          
				opp.Campaign_Score_Card__c = true;
				oppsToUpdate.add(opp);
			}
		}
	}

update oppsToUpdate;
}

 
Raj VakatiRaj Vakati
Try this pls
 
trigger AdworksTriggerForCampaignScoreCard on OpportunityLineItem (after update) {

	Set<Id> CurrentOppId = new Set<Id>();

	 for (OpportunityLineItem OppLnItem : Trigger.new){
	 if(OppLnItem.Product2.Name == 'Addressable'){
		CurrentOppId.add(OppLnItem.OpportunityId);
		}
}
	


List<Opportunity> relatedOpps = [SELECT Id,Name,Campaign_Score_Card__c FROM Opportunity where Id In  : CurrentOppId];

List<Opportunity> oppsToUpdate = new List<Opportunity>();

	for(Opportunity opp : relatedOpps){
	
			 opp.Campaign_Score_Card__c = true;
				oppsToUpdate.add(opp);
			 
		
	}

update oppsToUpdate;
}

 
Zoren DomingoZoren Domingo

Thanks Raj for your response, actually I already found another way to do this, but I will also try this. 

I let you know once I test it. appreciate your help.