Activity Forums Salesforce® Discussions How to Track field history on Opportunity Line Items?

  • Ajit

    Member
    April 21, 2016 at 8:29 am

    Salesforce does not provide any standard feature for history tracking on opportunity line items but through using a trigger we can get to this solution

     

    trigger OpportunityProucttRACKING on Opportunity (After insert, After update) {
    for(Opportunity t:trigger.new){
    List<String> NewList= new List<String>();
    if (t.HasOpportunityLineItem == true)
    {
    for(OpportunityLineItem OpLine: [SELECT CreatedBy.Name, Quantity, TotalPrice, LastModifiedDate, PriceBookEntry.Name, UnitPrice, ID FROM OpportunityLineItem WHERE OpportunityId =:t.Id] ) {
    NewList.add(OpLine.CreatedBy.Name);
    NewList.add(' on');
    String str1 = '' + opLine.lastModifiedDate;
    NewList.add(str1);
    }

    }
    }
    }

  • Ravi

    Member
    April 22, 2016 at 6:04 am

    Hi,
    You can do it using Custom Object and Trigger not with the Standard History Tracking.
    Step 1:
    Create a custom object(History_Tracking__c) to store your object history.
    Step 2:
    Create a Trigger on object where you want to track fields.
    Below is the sample code:

    trigger trackOppProduct on OpportunityLineItem (after insert, after update) {
    List<History_Tracking__c> hisTrackList = new List<History_Tracking__c>();
    //
    // Iterate through the OpportunityLineItems and create the History Tracking Record.
    //
    for (Integer i=0; i < Trigger.new.size(); i++) {

    OpportunityLineItem newCM = Trigger.new[i];
    if(Trigger.isInsert) {
    hisTrackList.add(new History_Tracking__c(OpportunityLineItem_Record_Id__c = newCM.Id,
    Object_Name__c = 'OpportunityLineItem',
    Field_Name__c = 'Status',
    Previous_Value__c = '',
    Current_Value__c = newCM.Status,
    Modified_Date_Time__c = System.now(),
    Modified_By__c = UserInfo.getUserId()
    ));
    } else if(Trigger.old[i].Status != newCM.Status){
    OpportunityLineItem oldCM = Trigger.old[i];
    hisTrackList.add(new History_Tracking__c(OpportunityLineItem_Record_Id__c = newCM.Id,
    Object_Name__c = 'OpportunityLineItem',
    Field_Name__c = 'Status',
    Previous_Value__c = oldCM.Status,
    Current_Value__c = newCM.Status,
    Modified_Date_Time__c = System.now(),
    Modified_By__c = UserInfo.getUserId()
    ));
    }
    }
    if(!hisTrackList.isEmpty()) {
    insert hisTrackList;
    }
    }

  • vishakha

    Member
    October 31, 2022 at 12:35 pm

    To track the field history on Opportunity line items is by using Custom Object and Trigger not with the Standard History Tracking.
    for this Create an object with the name History TrackingSecondly, creating a trigger on object where you want to track fields.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos