[SalesForce] Why can’t the Opportunity amount be changed by a trigger

I have more than one discount field in opportunitylineitem, so I created a custom field that sum all opportunity products total__c.

But I need see amount in forecasts, so I created a trigger that insert a total__c value in amount field, but don't work.

The amount field in opportunity can't be changed?

Thanks a lot.

Sample Code:

        trigger update_TotalPrice on OpportunityLineItem (after insert, after update) 
       {
             List <OpportunityLineItem> oliToInsert = new List <OpportunityLineItem> (); 
                for (OpportunityLineItem m : Trigger.new) 
                   { 
                      OpportunityLineItem oli = new OpportunityLineItem (); 
                      oli.TotalPrice = oli.Total__c;
                      oliToInsert.add(o);  
                   }
                       try
                         { 
                               insert oliToInsert; 
                         } 
                         catch (system.Dmlexception e)
                         {
                               system.debug (e);
                         }
             }

Best Answer

For opportunities with products, the amount is the sum of the related products. You cannot directly edit the amount unless the opportunity has no products. To change the amount for an opportunity that contains products, edit the sales price or quantity of the related products.

So you need to make sure that the amounts on the OpportunityLineItem are correct. Those you can update with workflow/apex code. But there are some limitations there as well, see https://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_opportunitylineitem.htm