Enterprise Territory Management – Auto Account Assignment using Apex

Use Apex code to auto assign Accounts on basis of Enterprise Territory Assignment rules

Enterprise Territory - Auto Account Assignment using Apex

Using Territory Management in Salesforce, we can auto assign territories to Account and give access to users working in common region. When we create Account, Territory Assignment rules automatically runs. On Account update we have a checkbox on page layout allowing to run Territory rules. However, Lightning experience does not support Territory Assignment checkbox yet on page layouts.

Unfortunately, Apex also does not support Account Assignment using Territory rules. Only way left is to use Salesforce API. Question is, just to run Enterprise Territory Management rules, should we import WSDL and convert it to respective Apex classes ? There must be some better way.

Then I remembered this article which I wrote around 5 years back. Instead of importing WSDL into Salesforce and converting it to Apex classes, we can take help of SOAP UI to find the request format and using HttpRequest, we can simulate request.

Below animation shows code in action :

Demo of Enterprise Territory Management Assignment rules using Apex in Salesforce
Demo of Enterprise Territory Management Assignment rules using Apex in Salesforce

How to get Salesforce SessionId in future Method, Batch Apex or any other Async Apex

Only challenge in invoking API from Queueable Interface is getting sessionId.

You might think that we can pass session Id directly to Queueable class/ It works in classic mode however I saw internal server error if user in Lightning experience mode. It works fine from anonymous Apex, but then fails if execution starts from Account Trigger.

For solution, Credit goes to @bigassforce for this Solution on twitter TIL series. We need to create a below Visualforce page to get sessionId and then use in our code. I tested this and works in both classic and Lightning.

Below code is self explanatory. Only catch was that we cannot get sessionId in asynchronous Apex and therefore we need to pass it as a parameter.

Related posts

5 thoughts on “Enterprise Territory Management – Auto Account Assignment using Apex”

  1. Hi Jitendra,

    This worked, but the limit is only 200 records in a soap update transaction.

    There is also a limit on webservice callouts 100.

    we have more accounts to update in a single tranaction is there any alternative

    Thank you

  2. Hey there,
    Nice blog!

    Quite understandable and handy when it comes to practicality. we have a similar blog on other aspects of the subject
    check it out and tell me what Ayou think of it.a feedback is always appreciated

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.