简体   繁体   中英

Apex trigger to default field values when adding opportunity line

I'm not a developer, but I'm attempting to learn since I've reached a point where I need code to customize and automate further. I've created a custom "Sales Price" field for Opportunity Products that I am using to replace the standard Sales Price field. I want the custom field to default with the price book entry list price (unitprice) value as does the standard Sales Price field. Then I have the standard Sales Price field getting updated to equal the custom Sales Price times the number of month terms (custom field that will be updated at Opportunity level and automatically populated in reflective custom field on Opportunity Products via trigger). I've created triggers for both the Sales Price value to default and the Month Terms to default, but neither seems to be working now. Below is the trigger for the Sales Price value when creating a new opportunity line item. Not sure how to get the price to default when adding a new product line item? It should only default when adding new since I don't want it to override any amount that they put in and save. But it also needs to work if they go back into the opp and add additional items later. Any input on this is greatly appreciated. I've spent hours searching posts and other documentation, but I don't have that natural developer brain, and I'm banging my head!

trigger SalesPricecustom on OpportunityLineItem (before insert) {
    Set<Id> pbeIds = new Set<Id>();
        for (OpportunityLineItem oli : Trigger.new) 
        pbeIds.add(oli.pricebookentryid);

    Map<Id, PricebookEntry> entries = new Map<Id, PricebookEntry>(
        [select UnitPrice from pricebookentry 
         where id in :pbeIds]);     

for (OpportunityLineItem oli :trigger.new){
     if(pricebookentry.unitprice <> null && oli.sales_price__c == null){

    oli.sales_price__c = entries.get(oli.pricebookEntryId).UnitPrice;  
  }
}} 

Thanks!

Could you describe your problem in other words? If you want to recalculate sales price field when old data is updated (not only inserted new lines), you should used "before update" event for this trigger, as here:

trigger SalesPricecustom on OpportunityLineItem (before insert, before update){
    //Here is your code
}

Also, you can check, which fields was changed, it will help you not to execute once again trigger logic, if other fields have been updated(use for this trigger context variables - Trigger.new, Trigger.old, Trigger.newMap, Trigger.oldMap).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM