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
PankajJhaPankajJha 

Hi Everyone, how to write trigger how to show account related opportunity releted product unique record count on account object with trigger.

how to show account related opportunity releted product unique record count on account object with trigger.

account -> opportunity -> product

thanks in advance.
ayu sharma devayu sharma dev
Hello Pankaj

Please create a Trigger on After Insert of OpportunityLineItem. In your Trigger Helper Class Method use the below logic:
 
List<Account> accToUpdate = new List<Account>();
Set<Id> oppIds = new Set<Id>();

for( OpportunityLineItem oppLine : Trigger.New ){
    oppIds.add( oppLine.OpportunityId );
}

for( Opportunity opp : [ SELECT Id, AccountId,
                       ( SELECT Id, Product2Id FROM OpportunityLineItems ) 
                        FROM Opportunity WHERE Id IN: oppIds ] ){
    
    Integer productCount = 0;
    Set<Id> processedProdIds = new Set<Id>();
    
    for( OpportunityLineItem oppLine : opp.OpportunityLineItems ){
        if( !processedProdIds.contains( oppLine.Product2Id ) ){
            productCount += 1;
            processedProdIds.add( oppLine.Product2Id );
        }
    }
    accToUpdate.add( new Account( Id = opp.AccountId, countField = productCount ) );   
}

if( accToUpdate.size() > 0 ){
    update accToUpdate;
}

If its helpful then mark this as the best solution.

Thanks and Regards
Ayush Sharma
Andrew GAndrew G
@ayush
Desk checking the code provided - what happens when there are more than one Opportunity per Account?
As I read the code, the values in the Account will only reflect the details of the last Opportunity.

@pankaj
To resolve the issue you will need to generate a Map<AccountId,Set<ProductIds>> and then set the countField to be the size of the associated Set of Product Ids

As an aside, I would question the placement of the code on the Opportunity Line Item - it would mean that as you are building the Opportunity, as each line item is inserted, the code will run.  And yet, as an Opportunity is being built, the sale is yet to be achieved, so is there real business value in counting the number of unique product codes if none of the Opportunities are converted to a sale?   And, if we are putting that code to run at this early stage, do we need to consider a Delete trigger?

Depending on the business need, would a Trigger on the Opportunity once it is "Closed/Won" be a better option?


Regards
Andrew