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
kamal3883kamal3883 

How to Identify New territory is assigned to Account in Apex?

Hi All,

Is there is any possible way to identify when a new territory is assigned to account. Actually when we assign territory to account a record of object ObjectTerritory2Association is created. But we cannot write trigger on ObjectTerritory2Association. So is there anything through which i can identify same in Apex. Anyother solution like creating fields or trigger on any object through which i can acheive same.
Neetu_BansalNeetu_Bansal
Hi Kamal,

Here you need to write trigger on Account, if its territory is populated, create a new record of ObjectTerritory2Association like below. Please fill the required fields of your object and update the API name as per your requirement.
trigger AccountTrg on Account( after insert, after update )
{
	List<ObjectTerritory2Association> ters = new List<ObjectTerritory2Association>();
	
	for( Account a : trigger.new )
	{
		if( a.Territory__c != null
			&& ( trigger.isInsert
				|| ( trigger.isUpdate && trigger.oldMap.get( a.Id).Territory__c != a.Territory__c )
				)
		)
		{
			ObjectTerritory2Association terri = new ObjectTerritory2Association( Name = 'Test' );
			ters.add( terri );
		}
	}
	
	if( ters.size() > 0 )
		insert ters;
}
Let me know if you need any other help.

Thanks,
Neetu
kamal3883kamal3883
Hi Neetu,

But how can i populate Territory on Account. 
Neetu_BansalNeetu_Bansal
Hi Kamal,

Its depends on your requirement, whether its while creating/editing Account on the standard layout, or you have created any visualforce page or there is any backend coding.

If not, then what is the criteria to populate territory?

Thanks,
Neetu
Ken KoellnerKen Koellner
I don't think Neetu solution applies; it is going the other way.   I think Kamal wants to do it the other way, detect when an ObjectTerritory2Association for an Account is inserted or deleted and take action on it.

Since triggers are not allowed on ObjectTerritory2Association, the only way I can think of doing it is via a batch sweep.  That is run a daily batch of ObjectTerritory2Association records inserted in the last day and process them.

 
JamieGJamieG
Did you ever find a solution to this problem?