function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Zoren DomingoZoren Domingo 

Apex Trigger - Create a record under opportunity, based on the OpportunityLineItem custom field.

Hi, can anyone can help me, I have little experience with apex trigger, I need to create a record base on the OpportunityLineItem custom field.

Multiple Records to create:

Campaign_Scorecard__c - custom object - Look-up relationship with Opportunity.

Balu_SFDCBalu_SFDC
Try below code.

trigger OpptLineITmesTrigger on OpportunityLineItem ( after insert,after update) {
      if(trigger.isAfter) {
        List<Campaign_Scorecard__c> insertCampns = new list<Campaign_Scorecard__c>();
        for (OpportunityLineItem oli: trigger.new){
           if(<Your Conditions>) {
            Campaign_Scorecard__c campRec = new Campaign_Scorecard__c(OpportunityId=oli.opportunityId,...........<Other your fields to popualte>)
            insertCampns.add(campRec);
           }
        }
        if(!insertCampns.isEmpty()) {
            try {
                insert insertCampns;
            }catch(exception e){
                OpportunityLineItem ol = trigger.new[0];
                ol.add.Error('your error');
            }
        }
    }
}
Zoren DomingoZoren Domingo

Hi, thank you for your help, but I have a problem - the record created is 2 records, I only need to create one record on each condition.

Here's my current code.

trigger AdworksTriggerForCampaignScoreCard on OpportunityLineItem (after insert, after update) {
    
    List<Campaign_Scorecard__c> scorecardToInsert = new list<Campaign_Scorecard__c>();    
    
    if(trigger.isAfter) {
        
        for (OpportunityLineItem oli: trigger.new){
            if(oli.Reporting_Length__c == 'Closed Loop Analysis (Client Data) Acxiom 60 Days') {
                   Campaign_Scorecard__c cs = new Campaign_Scorecard__c(Opportunity__c=oli.opportunityId);
                cs.Vendor_Measurement__c = 'Closed Loop Analysis (Client Data) Acxiom';
                cs.Days__c = '60';
                scorecardToInsert.add(cs);
               }
        }
        
    }
    
    try {
        insert scorecardToInsert;    
    } catch (system.Dmlexception e) {
            system.debug (e);
    }

}

Zoren DomingoZoren Domingo
I found my problem, the trigger is triggered everytime I hit the save button, how to validate or limit then record to avoid duplicates?
AshishkAshishk
Create a custom field on Setup > Customize > Opportunities > Opportunity Products i.e. OpportunityLineItem, on first save when you are creating record, you can update that flag on line item.
On next save you can check if that fiag i.e. custom field is set, so record should not be created.

Also try to use before trigger on line item and @future for creating records, so that there will not be a problem of limits.

Hope this works.

Thanks