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
Our Man In BananasOur Man In Bananas 

How to get record owner instead of current user?

I have the below trigger in my custom object. When a record is saved, the Manager field is being updated (via a lookup against the userInfo object)
trigger trg_LineManager on Request_for_System_Change__c (after insert, after update, before insert, before update) {

string LineManagerid = [SELECT Id, ManagerId from User where Id =: userinfo.Getuserid()].ManagerId;
    if (trigger.isBefore && (trigger.isInsert || trigger.isUpdate))
    {   
          for (Request_for_System_Change__c r : Trigger.new) {
                    
            r.Manager__c = LineManagerId;           
          } 
    }    
}



It works fine, except that when another user edits an existing record, the Manager field is being updated again with the current users manager.

So in fact I should be getting the Manager of the record Owner rather than the Mnaager of the current user.
Our Man In BananasOur Man In Bananas
Sorry, I clicked Post before I finished.
How can I modify that trigger to get the record owner for the Manager lookup, instead of the current user?
Abhishek BansalAbhishek Bansal
Hi Philip,

Just change your trigger code with the below code and everything will be fine :
trigger trg_LineManager on Request_for_System_Change__c (after insert, after update, before insert, before update) {

string LineManagerid = [SELECT Id, ManagerId from User where Id =: userinfo.Getuserid()].ManagerId;
    if (trigger.isBefore && trigger.isInsert)
    {   
          for (Request_for_System_Change__c r : Trigger.new) {
                    
            r.Manager__c = LineManagerId;           
          } 
    }    
}
Now the Manager field will be set only at the time when a record is craeted and not at the time when record is updated.
Please let me know if your requirement is something different or if you need any further help on this.

Thanks,
Abhishek Bansal.