0

I am trying to update Opportunity Lineitem custom field field1__c with Product2 custom field pickval__c. I have written a trigger when I update product I am getting CPU time limit exceeded exception

Trigger :

trigger trigOnProd on Product2(after update) 
{ 

  Set<Id> product2Ids= new Set<Id>();
  List<OpportunityLineItem> updateoli= new List<OpportunityLineItem>();

   for(Integer index = 0, size = trigger.new.size(); index < size; index++) {
    if(Trigger.old[index].pickval__c!= Trigger.new[index].pickval__c) {
      product2Ids.add(Trigger.new[index].Id);
    }
  }

   List<OpportunityLineItem> opliList = [SELECT Id,field1__C FROM OpportunityLineItem WHERE Product2Id IN:product2Ids];

  for(Product2 prod:Trigger.new){
      for(OpportunityLineItem ol : opliList ){
          ol.field1__C = prod.pickval__c;
          updateoli.add(ol);
      }

  }
  if(updateoli.size()>0){
  update updateoli;
  }


}

1 Answer 1

1

Don't place a loop in a loop when you can help it, and don't use temporary variables when you don't need to. Here's a modified version of your code:

trigger trigOnProd on Product2(after update) {
    Product2[] changedRecords = new Product2[0];
    for(Product2 record: Trigger.new) {
        if(record.Picklist__c != Trigger.oldMap.get(record.Id).Picklist__c) {
            changedRecords.add(record);
        }
    }
    if(changedRecords.isEmpty()) {
        return;
    }
    OpportunityLineItem[] items = [SELECT Product2Id FROM OpportunityLineItem WHERE Product2Id = :changedRecords];
    for(OpprtunityLineItem item: items) {
        item.Field1__c = Trigger.newMap.get(item.Product2Id).Pickval__c;
    }
    update items;
}

Depending on your other triggers, further optimizations are likely necessary.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .