+ Start a Discussion
Snita LalSnita Lal 

Auto Populate a Custom Lookup Field with the Current User

Hi

We have a custom lookup field that has been created on the Opportunity Line Item object called Product Owner. We would like this to be auto populated with the current user when left blank upon saving. 

We've tried to create a trigger to do this but run into errors upon saving the product line

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 = defaultuser.id;
    }
  }
}

Any help or advice would be much appreciated.

Thanks,

Snita

Best Answer chosen by Snita Lal
Ketankumar PatelKetankumar Patel
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();
    }
  }
}

try this. Userinfo.getUserId() will give you current user id.

All Answers

Vinoth Vijaya BaskerVinoth Vijaya Basker
Hi Snita, 

Please find the below example, 
 
trigger UpdateProductOwner on Opportunity (before insert, before update) {

    for(Opportunity opp : Trigger.new){
        if(opp.Product_Owner__c == null){
            opp.Product_Owner__c = UserInfo.getUserId();    
        }
    }

    
}

Thanks,
Vinoth
Ketankumar PatelKetankumar Patel
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();
    }
  }
}

try this. Userinfo.getUserId() will give you current user id.
This was selected as the best answer
Snita LalSnita Lal
Thanks for replying Vinoth.

I tried Ketankumar's trigger and it worked perfectly! Many thanks for your help and quick response.
Snita LalSnita Lal
Hi,

Triggers working perfectly, we're attempting to write the test class this morning and hitting a null value error.

Initially we didn't create the user and set the class to seealldata=true but realised that this isn't the best way to go about it. However, when we create the user inside the test class the value still returns the null value or doesn't know that the created user inserted the line.

Are we referncing this incorrectly? Any suggestions/advice would be very appreciated.

Thank you,

Snita
@isTest(seealldata=false)
private class TestUploadOwnerLookupField {

    static testmethod void initial(){
    
        id profileId = userinfo.getProfileId();

        User u2 = new User(Alias = 'nUr99', Email='newuser@testorg99.com', 
        EmailEncodingKey='UTF-8', LastName='Testing12', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = profileId , 
        TimeZoneSidKey='America/Los_Angeles', UserName='newuser99@testorg.com',External_Use__c='SRK1132AA',Operating_Country__c='Global',Region__c='Global' ,Team__c='Client Services - Global');
        insert u2;   
    
        Account a = new Account(Name = 'Test A',
        BillingCountry = 'UK',
        Ownership_Type__c = 'Private',
        Phone = '07826533392',
        Industry = 'Property development & management',
        Type = 'Customer Direct');
        insert a;
    
        Opportunity o = new Opportunity ( Name='Test A',AccountId = a.Id,
        RecordTypeID = '01290000000Soum',
        CloseDate = Date.today(),
        Type = 'New Customer',
        StageName = 'Closed Won',
        Bid_Submission_Date__c = Date.today(),
        Service_Start_Date__c = Date.today(),
        Governance_Compliance__c = TRUE,
        Brand_Name__c = 'Absotherm',
        ES_Office__c = 'Barking',
        Term__c = 1 );
        insert o;
        
        OpportunityLineItem lineItem1 = new OpportunityLineItem (OpportunityID=o.id,
        PricebookEntryId = '01u90000005gFxNAAU',
        UnitPrice = 1000,
        Gross_Margin_Percentage__c = 10,
        Quantity = 1);
        insert lineItem1;
        
        system.assertNotEquals(LineItem1.Product_Owner__c, null);
        system.assertEquals(LineItem1.Product_Owner__c, u2.name);  
           }
}

 
Snita LalSnita Lal
Thanks we managed to fix this one, no need for responses. We didn't realise that lookup fields in Salesforce and the value that is contained within them was not an ID field but a string. We've pasted the working test class below;
 
@isTest(seealldata=false)
private class TestUploadOwnerLookupField {

    static testmethod void initial(){
    
        id profileId = userinfo.getProfileId();

        User u2 = new User(Alias = 'nUr99', Email='newuser@testorg99.com', 
        EmailEncodingKey='UTF-8', LastName='Testing12', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = profileId , 
        TimeZoneSidKey='America/Los_Angeles', UserName='newuser99@testorg.com',External_Use__c='SRK1132AA',Operating_Country__c='Global',Region__c='Global' ,Team__c='Client Services - Global');
        insert u2;   
    
        Account a = new Account(Name = 'Test A',
        BillingCountry = 'UK',
        Ownership_Type__c = 'Private',
        Phone = '07826533392',
        Industry = 'Property development & management',
        Type = 'Customer Direct');
        insert a;
    
        Opportunity o = new Opportunity ( Name='Test A',AccountId = a.Id,
        RecordTypeID = '01290000000Soum',
        CloseDate = Date.today(),
        Type = 'New Customer',
        StageName = 'Closed Won',
        Bid_Submission_Date__c = Date.today(),
        Service_Start_Date__c = Date.today(),
        Governance_Compliance__c = TRUE,
        Brand_Name__c = 'Absotherm',
        ES_Office__c = 'Barking',
        Term__c = 1 );
        insert o;
        
        OpportunityLineItem I = new OpportunityLineItem (OpportunityID=o.id,
        PricebookEntryId = '01u90000005gFxNAAU',
        UnitPrice = 1000,
        Gross_Margin_Percentage__c = 10,
        Quantity = 1);
        insert I;
        
        system.assertNotEquals(I.Product_Owner__c, I.id);
        system.assertEquals(I.Product_Owner__c, u2.name);  
           }
}

 
Karen Davis 1Karen Davis 1
Thanks for this thread! I needed the same thing,  had never written anythign in Apex and was able to use this to write my own trigger (on a different object). Appreciate the help!
Artem Skobrev 8Artem Skobrev 8
How would I alter this trigger in order to populate a specific field called 'Requestor' when a new Case is created within an Opportunity. So basically when I go into an Opportunity and create a new Case, I would like for the Requestor field in the new case to auto populate with the current Username of the person logged in. 

Any help is much appreciated!
Ankit Kalsara 14Ankit Kalsara 14
Hi,

I wrote the same code and it populates the current user info after I save the record.
I need to pre-populate the current user info when I create the new record.
Below is my trigger code.

trigger populate_current_user on Applications_Time_Tracking__c (before insert) {

    // populate the current user name on record creation 
    for(Applications_Time_Tracking__c tt : Trigger.new){

        if(tt.User__c == null){

            tt.User__c = UserInfo.getUserId();   
        }
    }


Can you please help.