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
Ankit Kalsara 14Ankit Kalsara 14 

How to auto-populate user in custom lookup field

Hi team,

I have written trigger to auto-populate current user on custom lookup field for custom object. However it does not work. Any idea how do we populate current user on custom lookup field ?

trigger populate_current_user on Applications_Time_Tracking__c (before update) {

    // populate the current user name on record creation 
   for (Applications_Time_Tracking__c record : Trigger.new) {    
      record.User__c = UserInfo.getUserId();    
   }
}
ApuroopApuroop
Below code is same the as yours but with before insert too.I see in the comment, populate the current user on record creation.
trigger populate_current_user on Applications_Time_Tracking__c (before insert, before update){
    // populate the current user name on record creation 
   for(Applications_Time_Tracking__c record : Trigger.new) {    
      record.User__c = UserInfo.getUserId();    
   }
}

Things to check:
Make sure the trigger is active.
Make sure User__c is a Lookup field to the User object

I just checked the same functionality on Contact by creating a new lookup field to User, it is working as expected.
NagendraNagendra (Salesforce Developers) 
Hi Ankit,

Sorry for this issue you are facing.

May I suggest you please try the sample code below which works fine for me.
trigger updatefield on OpportunityLineItem (after insert) {
//  user defaultuser = [select id from user where name = 'default user'];
  for (OpportunityLineItem record:trigger.new) {
    if(record.Product_Owner__c ==null) {
      record.Product_Owner__c = userinfo.getUserId();
    }
  }
}
Hope this helps.

Kindly mark this as solved if the reply was helpful so that it gets removed from the unanswered queue which results in helping others who are facing a similar issue.

Thanks,
Nagendra
 
Ankit Kalsara 14Ankit Kalsara 14

Hi Apuroop, Nagendra,

The code provided by you works well after the record is created.

My requirement is to populate current user when the user inputs the data for the object (before he clicks on save button)