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
Harish Chekurthi 9Harish Chekurthi 9 

Creating a workflow to stop deactivating user linked to a Teritorry

Hi,
I want to create a workflow to stop deactivating a USer if he/she is linked to a Territory.

For instance, a CDM who stopped working at my org and I need to create a workflow to stop deactivating him/her if the CDM is linked to Territory.

Could anyone please help me as this is urgent.Please see my below workflow.
I am trying to include the Workflow as Territory:CDM equals to True,
Territory Owner is not equal to Deactivate.
The above workflow is not wrking. could someone help me out please?
Arvind KumarArvind Kumar
Hi,

You cannot achieve this by workflow. you have to make validation rule by trigger.  
Harish Chekurthi 9Harish Chekurthi 9
Hi Arvind, Could you please help me out how to write the validation rule by trigger.
Arvind KumarArvind Kumar
Hi,

Use below trigger it will be helpful for you.
 
trigger UsernotInactive on User (before update) 
{
   
   Set<Id> usrIds = new Set<Id>();
   List<UserTerritory2Association> usrTrrList;
   
   for(User usr : [Select Id, Username, IsActive from User where UserName =: 'Username'])
   {
       usrIds.add(usr.Id);
   }
   
  
   
   usrTrrList = new List<UserTerritory2Association>([SELECT Id, UserId FROM UserTerritory2Association where UserId  IN : usrIds]);
   
   if(usrTrrList != null && usrTrrList.size()>0)
   {
   for(User usObj : Trigger.new)
   {
       if(usOBj.IsActive==false)
          usObj.addError('You can deactive this user');
   }
  }
   
}

Follow the below steps.
1.) If more than one user is assigned to Territory. Then you have to make a change in the trigger.
     In Soql query for user Object : [Select Id, Username, IsActive from User where UserName =: 'Username'].
2.)  Use below query for more than one user.
     [Select Id, Username, IsActive from User where UserName =: 'Username' OR UserName =: 'Username']

if you have any query please let me know.

Thanks,
Arvind Kumar