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
Allen ManamelAllen Manamel 

How to change the contact owner in Apex Controller -- URGENT

Hi All,

I have a piece of code in my apex controller in which I am trying to update the contact owner but it does update.

public pagereference submit() {

 if(contact.Region__c == '3')
       
           {
        
        
        // Fetch Assigned Users in Region 3 Territory
        
              List<UserTerritory2Association> UsersInRegion3 = new List<UserTerritory2Association>([SELECT Id, RoleInTerritory2, Territory2Id, UserId from UserTerritory2Association WHERE Territory2Id= '0MIr00000004CJp']);
              System.debug(UsersInRegion3);
              
              
              for(UserTerritory2Association a: UsersInRegion3)

                 {
   
                   
           
                   if(contact.UserCategory__c == 'FirstCategory' && a.RoleInTerritory2 == 'Regional Counselor A - K')
      
                        contact.OwnerId = a.UserId;
                   
                   else if (contact.UserCategory__c == 'SecondCategory' && a.RoleInTerritory2 == 'Regional Counselor L - Z')
      
                        contact.OwnerId = a.UserId;
           
   
                }

        
           }

Please let me know ASAP, how can I achieve this?
Sagar PatilSagar Patil
Code looks good syntactically. First check whether the list you are fetching through SOQL have records or not.

Try to debug each line in For loop using System.debug statement and check where it goes wrong and if it enters in IF-ELSE loop, check the value of a.UserId. so that you will get some clue.

Contact's ownerid might be not updating due to the conditions mentioned in the IF-ELSE loop haven't satisfied.