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
sean*harrisonsean*harrison 

Inserting Territory via AccountShare

I seem to be getting contradictory results when I attempt to insert an AccountShare record for Territory management.

 

If I do this:

			List<Territory> newTerrsToAssign = new List<Territory>([SELECT Id FROM Territory WHERE Name in :terrNames]);
			List<Group> newGroupsToAssign = new List<Group>([SELECT Id FROM Group WHERE RelatedId in :newTerrsToAssign]);
			List<AccountShare> newSharesToAssign = new List<AccountShare>();
			for (Group g : newGroupsToAssign) 
			{
				AccountShare share = new AccountShare(UserOrGroupId=g.Id, AccountId=acctId);
				share.AccountAccessLevel='Edit';
				share.OpportunityAccessLevel='None';
				share.CaseAccessLevel='None';
				newSharesToAssign.add(share);
			}
			return Database.insert(newSharesToAssign);

 

I get this: 

Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: AccountAccessLevel (Access level should not be specified on territory manual assignment): [AccountAccessLevel] 


But if I do this:

			List<Territory> newTerrsToAssign = new List<Territory>([SELECT Id FROM Territory WHERE Name in :terrNames]);
			List<Group> newGroupsToAssign = new List<Group>([SELECT Id FROM Group WHERE RelatedId in :newTerrsToAssign]);
			List<AccountShare> newSharesToAssign = new List<AccountShare>();
			for (Group g : newGroupsToAssign) 
			{
				AccountShare share = new AccountShare(UserOrGroupId=g.Id, AccountId=acctId);
				// share.AccountAccessLevel='Edit';
				share.OpportunityAccessLevel='None';
				share.CaseAccessLevel='None';
				newSharesToAssign.add(share);
			}
			return Database.insert(newSharesToAssign);

 

I get this:

Insert failed. First exception on row 1; first error: REQUIRED_FIELD_MISSING, missing required field: AccountAccessLevel: [AccountAccessLevel] 


Bummer. What am I missing here?

sean*harrisonsean*harrison

Well, one thing I'm missing is that I was grabbing the ids of groups of type "Territory" and "TerritoryAndSubordinates."  Making the following changes has now allowed the insert:

 

List<Territory> newTerrsToAssign = new List<Territory>([SELECT Id FROM Territory WHERE Name in :terrNames]);
List<Group> newGroupsToAssign = new List<Group>([SELECT Id FROM Group WHERE Type = 'Territory' AND RelatedId in :newTerrsToAssign]);
List<AccountShare> newSharesToAssign = new List<AccountShare>();
for (Group g : newGroupsToAssign) 
{
  AccountShare share = new AccountShare(UserOrGroupId=g.Id, AccountId=acctId);
  // share.AccountAccessLevel='Edit';     // Don't specify these as you'll get
  // share.OpportunityAccessLevel='None'; // FIELD_INTEGRITY_EXCEPTIONs
  // share.CaseAccessLevel='None';        //
  newSharesToAssign.add(share);
}
return Database.insert(newSharesToAssign);