+ Start a Discussion

Trigger Question



   For a particular product we do not want that sales rep. change unitprice and quantity. I wrote this trigger but its throwing me an error. 



trigger HealthOppProductTrigger on OpportunityLineItem (before insert, before update) {
 list <opportunitylineitem> opplines = trigger.new;
 for (Opportunitylineitem opp : opplines)
 if(trigger.isInsert ||  Trigger.oldmap.get(opp.id).quantity!=opp.Quantity || Trigger.oldmap.get(opp.id).unitprice!=opp.unitprice  )
 if(opp.Quantity!=200.00 ||  opp.unitprice!=18 )
    opp.quantity.addError('Quantity Should be 200 and Unit Price should be $18');
        insert opp;
Error Message at Runtime : Apex trigger HealthOppProductTrigger caused an unexpected exception, contact your administrator: iHealthOppProductTrigger: execution of BeforeInsert caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.iHealthOppProductTrigger: line 20, column 10
Appreciate your help.  



You don't need to call insert on the objects in the trigger. Just remove the insert call.


Also, based on what I see here you should be able to use a formula validation rule anyway and avoid the code effort. Have you looked at them?


You need not write the insert command in trigger because the trigger is executing due the "Before insert" command. You just need to remove the "insert opp;" line from you trigger.