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
elossoelosso 

Need to use a trigger when a field updates

Here is the trigger I'd like to create:

 

I have an Opportunity Product with a Actual Impressions field. I use the Quantity to forecast the likely impressions; however, at the end of each month, I go back and populate Actual Impressions. When I change Actual Impressions, I'd like to launch a trigger that update the Quantity field to the value of the Actual Impressions field. 

 

Any help would be appreciated!

  

My code so far:

 

trigger updateQuantity on OpportunityLineItem (after update) {

for (OpportunityLineItem newQuantity : Trigger.new) {
    OpportunityLineItem oldQuantity = Trigger.oldMap.get(newQuantity.Id);
    if (oldQuantity.Actual_Impressions__c != newQuantity.Actual_Impressions__c) {
        // this is where I don't know how to update a given field
    }
}

}
Best Answer chosen by Admin (Salesforce Developers) 
Sean TanSean Tan

Is the quantity field on the OpportunityLineItem as well? If so you should change the trigger to before update, something like this should do:

 

trigger updateQuantity on OpportunityLineItem (before update) {
	
	for (OpportunityLineItem newQuantity : Trigger.new) {
		OpportunityLineItem oldQuantity = Trigger.oldMap.get(newQuantity.Id);
		if (oldQuantity.Actual_Impressions__c != newQuantity.Actual_Impressions__c) {
			newQuantity.Quantity__c = newQuantity.Actual_Impressions__c;
		}
	}
	
}

 

All Answers

Sean TanSean Tan

Is the quantity field on the OpportunityLineItem as well? If so you should change the trigger to before update, something like this should do:

 

trigger updateQuantity on OpportunityLineItem (before update) {
	
	for (OpportunityLineItem newQuantity : Trigger.new) {
		OpportunityLineItem oldQuantity = Trigger.oldMap.get(newQuantity.Id);
		if (oldQuantity.Actual_Impressions__c != newQuantity.Actual_Impressions__c) {
			newQuantity.Quantity__c = newQuantity.Actual_Impressions__c;
		}
	}
	
}

 

This was selected as the best answer
elossoelosso
This worked great! Thank you, Sean!
SFDCTech1SFDCTech1

i have a trigger in which i have code like this

 

 

where i have a field count which counts when status changes from open to closed , converted to closed but my code even counting whenever status changes from closed to closed which i dont want. please helpout, i am new to this.

 

 if((OPP.Count__c==OPPOLD.Count__c)&&OPP.Status__c=='Closed')