You need to sign in to do that
Don't have an account?
Enry
Trigger opportunity Product Lost
Hi,
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:
1)Copy Unit Price in a custom field named OfferedPrice__c
2) 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?
Thank you in advance.
BR
The below code should be sufficient.
for (OpportunityLineItem opproduct: Trigger.new){
if (opproduct.Lost__c==True && Trigger.oldMap(opproduct.Id).Lost__c != opproduct.Lost__c){
opproduct.OfferedPrice__c= opproduct.UnitPrice;
opproduct.UnitPrice = 0;
}
}
replace your Trigger with the code given below
trigger LostProduct on OpportunityLineItem (before update)
{
for (OpportunityLineItem opproduct: Trigger.new){
if (opproduct.Lost__c==True){
opproduct.OfferedPrice__c= opproduct.UnitPrice;
opproduct.UnitPrice=0;
}
}
}
Thanks to all! you are very kind.
I think that the Esp-MP is near the solution,because if the checkbox Lost__c isn'tn modified i must not execute the trigger's code.This is the code but i get an error:
ERROR:
Please help me.
I am sorry this is one of my first trigger.
KR.
Try the solution which i have provided .. it Will work fine . and if you want to include the condition for trigger.old also i will be posting the condition soon.
Thank you Saurabh Dua!
Your trigger work well,but it fire also if the checkbox Lost__c isn't modified.
Please can you help me with the trigger.old condition?
Thank you very much!
Thank to all! It works: