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

Summarize the accounts based on territory



  I want to display the number of accounts per territory on a record.Accounts can be tied to more than1 territory.So please share some sample code to do this.




Writing out all the code would take a lot of time, but here's general flow of how I would code the trigger:


1. Use Schema.DescribeFieldResult and Schema.PicklistEntry to get territory values from field

2. Create a Map of <String, Integer> with the territory values from above as the key and 0 as the value

3. Get list off all Account records by SOQL. If possible get a subset list, like only accounts belonging to a specific sales rep, etc.

4. Loop through list of Accounts

5. On each Account do a List<String> acctTerrs = Account.Territory__c.split(';');

6. As a nested loop, go through above list of strings as keys to the map, increase the related integer value


After the loops are complete, you'll have the count of the number of times a territory is selected as an option across your list of Accounts.