I have a custom checkbox Lost__c on opportunity product so when you edit the product added on the opportunity, you can set that the product isn’t sold.
I want that if the checkbox is true:
Copy Unit Price in a custom field named OfferedPrice__c
Set UnitPrice to zero
I have written the following code:
trigger LostProduct on OpportunityLineItem (before update)
{
Set<Id> Ids = new Set<Id>();
\\ GET THE NEW OPPORTUNITY lINE ITEM ID
for (OpportunityLineItem oppli: Trigger.new){
Ids.add(oppli.id);
}
\\ GET THE OLD OPPORTUNITY lINE ITEM
List <OpportunityLineItem> oppsec=[Select Id,OfferedPrice__c,UnitPrice From OpportunityLineItem Where id in: Ids];
List<OpportunityLineItem> ListOpp = new List<OpportunityLineItem>();
for (OpportunityLineItem opproduct: Trigger.new){
if (opproduct.Lost__c==True){
opproduct.OfferedPrice__c= opproduct.UnitPrice;
Listopp.add(opproduct);
}
}
\\ SET FIELDS OF THE OLD RECORD
oppsec[0].OfferedPrice__c=Listopp[0].OfferedPrice__c;
oppsec[0].UnitPrice=0;
update(Oppsec);
}
but i get this error message:
Apex trigger LostProduct caused an unexpected exception, contact your administrator: LostProduct: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 00kJ0000006in6cIAA; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 00kJ0000006in6c) is currently in trigger LostProduct, therefore it cannot recursively update itself: []: Trigger.LostProduct: line 23, column 1
Where i am wrong? Do is necessary get the old record?