1

I am trying to find a solution to getting all accounts in a users territory or territories with soql. I am not finding much info about it anywhere with Enterprise Territory Management.

EDIT: What I am confused about after looking at the ERD is how to get accountids associated to the rules? From what I see is objects with assignment rules but not specific object holding the ids associated with the rules.

2
  • What have you tried so far? Where are you stuck? Have you looked at the ERD at all?
    – Adrian Larson
    Commented Oct 25, 2018 at 13:49
  • Hello Adrian. I looked at the ERD and I can see how to get users in a territory. But what im am confused about is I dont see any account ids in any of the objects on the ERD.
    – DerrickE
    Commented Oct 25, 2018 at 13:57

1 Answer 1

6

You want to look at ObjectTerritory2Association.

Represents an association (by assignment) between a territory and an object record, such as an account. Available only if Enterprise Territory Management has been enabled for your Salesforce org.

For instance, if you have a specific Territory2 record and you want to get all related Account records, it might look like:

Territory2 territory; // = some value
List<Account> relatedAccounts = [
    SELECT Name FROM Account WHERE Id IN (
        SELECT ObjectId FROM ObjectTerritory2Association
        WHERE Territory2Id = :territory.Id
    )
];
4
  • ObjectTerritory2Association... Right in front of my face. Thanks for pointing me in the right direction.
    – DerrickE
    Commented Oct 25, 2018 at 16:01
  • @DerrickE If this answer addressed your problem, please consider accepting it by clicking on the check mark/tick to the left of the answer, turning it green. This marks the question as resolved to your satisfaction, and awards reputation both to you and the person who answered. If you have >= 15 reputation points, you may also upvote the answer if you wish. There is no obligation to do either.
    – Adrian Larson
    Commented Oct 26, 2018 at 1:07
  • Ahh okay.. I always wondered how to mark as the best answer. thank you
    – DerrickE
    Commented Oct 26, 2018 at 2:59
  • I used Adrian's code in the Execute Anonymous window and added the following to set the territory value. Territory2 territory = new Territory2(); territory.Id = 'some value'; I got a value for a Territory2 object from the query: SELECT Id, ObjectId, Territory2Id, AssociationCause, SobjectType, IsDeleted FROM ObjectTerritory2Association. I also added a debug loop to see the result: for (Account acc : relatedAccounts) { system.debug(acc); }//next Commented Nov 23, 2020 at 10:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .