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
SCh9SCh9 

Code/Trigger to get count of number of different Product groups, the Assets of each Account belong to at the Account object level

I am trying to achieve a solution for the following problem -
For each Account, I want to know the assets of an account belongs to how many different productGroups (to see products belonging to how varied of product groups each Account(Client) is buying from us)
ProductGroup is a formula field on Assets which gets the value from Products object ( ProductGroup is a picklist on Products)


For example,
If I have, Product groups - P1, P2, P3, P4, P5; Assets - A1, A2, A3, A4 and A1, A2, A4 --> P1 A3 --> P4
I want the count to be 2 because all the assets of this account belongs to 2 different product groups.
From this, I would know Account X is buying our products from 2 productGroups.


My approach - To get the no. of assets in each productGroup, my approach would be for each picklist value in Product Group, using SOQL query , SELECT COUNT(AssetID) from Assets__c GROUP BY Product_Group__c
For each productGroup, get the number of records where the above mentioned countVariable is > 0
Copy this value on to a new custom field(BreadthOfAssets) on Account object.

Am I right?
Do i need to write a trigger on Asset or Account for this and need help  in coding this.
Thank you
v varaprasadv varaprasad
HI ,

You need to write a trigger on asset object : 
please check sample code below, I have not tested may be syntax errors will happen.
 
triiger updateAccount on Asset__c(After insert,after update,after delete,after undelete){
   set<id> accIds = new set<id>();
   
   if(trigger.isAfter && (trigger.isinsert || trigger.isUpdate || trigger.isUndelete)){
      for(Asset__c ast : trigger.new){
	  if(ast.accountid != null){
	      accIds.add(ast.accountid );
	  
	  }
	  
	  }
   
   
   }
   
   if(trigger.isAfter && trigger.isdelete){
         for(Asset__c ast : trigger.old){
	  if(ast.accountid != null){
	      accIds.add(ast.accountid );
	  
	  }
	  
	  }
   
   
     }
	 
	list<account> lstAccounts = [select id,name,(SELECT id,productgroup__c,accountid from Assets__c where productgroup__c != null)
	from account where id in :accIds];
	list<account> updAccs = new list<account>();
	
	
	
	for(account ac : lstAccounts){
	
	set<string> pgcount = new set<string>();
	for(Assets__c aste : ac.Assets__r){
	   pgcount.add(aste.productgroup__c);  
	
	}
	ac.BreadthOfAssets = pgcount.size();
	updAccs.add(ac);
	}
	
if(updAccs.size()>0){
    update updAccs;
}




}



Hope this helps you.
if above information is informative please mark it as the best answer. 

Thanks
Varaprasad