Enterprise Territory Management is an account-sharing model that grants access to accounts based on the attributes of the accounts. A territory is a collection of the account records and business users where the users have minimum read access to the accounts, irrespective of who owns the account records. By enabling territory settings, users can get read, read/write, or owner-like access to the accounts in that territory. For comprehensive instructions for implementing this feature, see the Enterprise Territory Management Implementation Guide.
Salesforce allows you to add accounts manually to territories or define account assignment rules that assign accounts to territories for you. If you want the rule to run automatically when a user creates or updates an account, then you need to understand how the dynamic assignment will work when an account record is updated via UI or API.
1. If the account is updated via the UI, "Evaluate this account against territory rules on save" checkbox needs to be selected. You can refer the article below to add this checkbox to the page layout:
https://help.salesforce.com/articleView?id=000004725&type=1
2. If the account is updated via API,
AssignmentRuleHeader
must be specified in the update()
call of an Account for the territory assignment rules to be applied as per the SOAP API Developer Guide.Make sure that the Active checkbox is selected on the rule edit page, or else rules won't run automatically.
To test the automatic assignment of territories using the 2nd approach, I created a territory assignment rule DEMO_TERRITORY. I configured this rule in such a way that it will assign an account record to a territory with the same name, i.e. DEMO_TERRITORY, in my territory hierarchy.
I also created a custom field "Account Territory" on Account object; when this field is populated with the name of the territory, a trigger is invoked which will then call a future method.
This future method contains the main logic to run the assignment rules. It will create a soap envelope, populate the sessionId and relevant account Ids for which assignment rules need to run. Finally using HTTP Request and Response objects, I invoked this SOAP web service.
All territory assignment rules are applied for the account(s) if for the element name
useDefaultRule
, value is true. If the value is false, then no territory assignment rules are applied.This is the source code of the future method.
I also updated
Run_Territory__c
to false
in the webservice call to prevent recursive future calls as I was getting System.CalloutException: Callout loop not allowed
exception.Please remember that the maximum records in an update request can be 200. You can't just dump in thousands of records in an API call.