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
DustinLHDustinLH 

User Lookup Field to Change Owner

Does anyone have any code that takes a custom user lookup field and changes the owner of the record to match and vice versa (changing owner updates user lookup field)?

 

I have a use case where I need to force the user to identify the owner of the record during the creation of the record and not rely on their memory to change the owner after the fact.

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox
trigger SyncField on anObject(before insert, before update) {
  for(anObject ao:Trigger.new)                                       // For each record
    if(Trigger.isInsert)                                             // If we're inserting
      ao.OwnerId = ao.Assigned__c;                                   // Assign ownership from Assigned__c
    else                                                             // Otherwise (an update)
      if(ao.OwnerId != Trigger.oldMap.get(ao.id).OwnerId)            // If ownership has changed
        ao.Assigned__c = ao.OwnerId;                                 // Place the new owner is assigned
      else                                                           // Otherwise (owner not changed, is an update)
        if(ao.Assigned__c != Trigger.oldMap.get(ao.id).Assigned__c)  // If the Assigned__c field changed
          ao.OwnerId = ao.Assigned__c;                               // Assigned ownership from Assigned__c
}

I think this should just about cover your request... Change object names and field names to suit your environment.

All Answers

doubleminusdoubleminus

It may help to know a little more about your use case here. I guess what I don't understand is...if the user is settig a User lookup field...why don't they also just change the owner?

 

Otherwise, this can be done easily with a validation rule (record cannot be saved until User lookup field matches record Owner field) or with a simple Apex trigger. Once I know a little more detail, I can assist with the trigger if that's the correct option.

DustinLHDustinLH

The custom object record (Referral) the user is creating is always going to be re-assigned to another user. We have cases where they forget to change the owner, since you have to do it after the record is created. Since the owner is not changed, the record never gets addressed by the user it was supposed to go to and customer service is impacted.

 

The custom field (Assigned) would be required and force the user to identify the user they wish to assign the record to. I cannot use a validation rule, because they cannot change the owner during the creation of the record. You cannot change owners in edit mode, only from viewing the record.

 

My hope was to have a trigger that would change the owner for them when they populate the field. To avoid confusion, or other issues, I would want the trigger to also update the field if the owner was changed the normal way just so that it is always in sync with the owner field.

 

Does that make sense? If not let me know.

sfdcfoxsfdcfox
trigger SyncField on anObject(before insert, before update) {
  for(anObject ao:Trigger.new)                                       // For each record
    if(Trigger.isInsert)                                             // If we're inserting
      ao.OwnerId = ao.Assigned__c;                                   // Assign ownership from Assigned__c
    else                                                             // Otherwise (an update)
      if(ao.OwnerId != Trigger.oldMap.get(ao.id).OwnerId)            // If ownership has changed
        ao.Assigned__c = ao.OwnerId;                                 // Place the new owner is assigned
      else                                                           // Otherwise (owner not changed, is an update)
        if(ao.Assigned__c != Trigger.oldMap.get(ao.id).Assigned__c)  // If the Assigned__c field changed
          ao.OwnerId = ao.Assigned__c;                               // Assigned ownership from Assigned__c
}

I think this should just about cover your request... Change object names and field names to suit your environment.

This was selected as the best answer
DustinLHDustinLH

Thanks sfdcfox! I think we are close, but I am getting the following error:

 

ErrorError: Compile Error: Method does not exist or incorrect signature: [LIST<Referral__c>].get(Id) at line 6 column 23

 

Here is the code:

 

trigger AssignOwner on Referral__c(before insert, before update) {
  for(Referral__c r:Trigger.new)                                         // For each record
    if(Trigger.isInsert)                                                 // If we're inserting
      r.OwnerId = r.Assigned__c;                                         // Assign ownership from Assigned__c
    else                                                                 // Otherwise (an update)
      if(r.OwnerId != Trigger.old.get(r.id).OwnerId)                     // If ownership has changed
        r.Assigned__c = r.OwnerId;                                       // Place the new owner in Assigned__c
      else                                                               // Otherwise (owner not changed, is an update)
        if(r.Assigned__c != Trigger.oldMap.get(r.id).Assigned__c)        // If the Assigned__c field changed
          r.OwnerId = r.Assigned__c;                                     // Assigned ownership from Assigned__c
}

 


sfdcfoxsfdcfox

Had a typo... I updated the original post to change old to oldMap. This should work.

DustinLHDustinLH

sfdcfox

 

This works great! Thank you so much for the help! If you have a second, can you look at my test class? I am only getting 36% coverage for the trigger and am not sure what to do with it.

 

@isTest
private class testReferralAssignOwner {
    static testMethod void testReferralAssignOwner() {
        List<Referral__c> myReferrals = new List<Referral__c>();
                
        /* Create 1 test account */
        Account a = new Account(name = 'testAccount');
        insert a;
        
        /* Create 100 test referrals */
        for(Integer i=0; i < 100; i++){
            Referral__c r = new referral__c();
            r.Client_Name__c = a.id;
            r.Phone__c = '6308920202';
            r.Assigned__c = '00580000001k765';
            myReferrals.add(r);

        }
        
        test.startTest();
        insert myReferrals;
        test.stopTest();
        
                
        /*there should be 100 referrals as you iterated 100 times*/
        List<Referral__c> createdReferrals = [select id from Referral__c where ownerid = '00580000001k765' AND assigned__c = '00580000001k765'];
        System.assertEquals (createdReferrals.size(), 100);
     
}
}

 

sfdcfoxsfdcfox

You tested only the insert trigger portion. Your entire test class should look more like this:

 

@isTest
private class testReferralAssignOwner {
  static testMethod void test() {
    List<User> testUsers = [select id from user where isactive = true limit 2];
    Account a = new Account(Name='test');
    insert a;
    List<Referral__c> refs = new List<Referral__c>();
    refs.add(new Referral__c(Client_Name__c=a.id,Phone__c='12345',Assigned__c=testUsers[0].Id));
    refs.add(new Referral__c(Client_name__c=a.id,Phone__c='12345',Assigned__c=testUsers[1].Id));
    insert refs;
    system.assertEquals(refs[0].OwnerId,testUsers[0].Id); // OwnerId should equal Assigned__c;
    system.assertEquals(refs[1].OwnerId,testUsers[1].Id); // OwnerId should equal Assigned__c;
    refs[0].OwnerId = testUsers[1].Id;
    refs[1].Assigned__c = testUsers[0].Id;
    update refs;
    system.assertEquals(refs[0].Assigned__c,testUsers[1].Id); // Assigned__c should equal OwnerId now
    system.assertEquals(refs[1].OwnerId,testUsers[0].Id); // OwnerId should equal Assigned__c now
  }  
}

Note that our code does assume that Assigned__c will always be populated (it'll error otherwise). Ordinarily this won't happen, but it could if you forgot to map a field on an import, for example.

DustinLHDustinLH

sfdcfox

 

I am getting this error with that test:

 

ErrorError: Compile Error: Method does not exist or incorrect signature: system.assertEquals(Id) at line 16 column 5

 

Thanks again for all of your help. Hopefully we are close!

sfdcfoxsfdcfox

Updated that last post, as well. I wasn't appearantly paying attention.

DustinLHDustinLH

sfdcfox

 

It looks like it is getting a user id when it shouldn't be. This is the message I am seeing when I run the test and it fails:

 

System.AssertException: Assertion Failed: Expected: null, Actual: 00580000001k6g1AAAClass.testReferralAssignOwner.test: line 11, column 1

 

The 00580000001k6g1AAA is a user id.

DustinLHDustinLH

sfdcfox

 

I just wanted to follow up and see if you had any suggestions as to why the test would be expecting a null in that result but getting an id instead. Please let me know if you can assist. Thanks again for your help!

cymartzcymartz

I'm getting that same error when running the test method. Were you ever able to figure this out?

DustinLHDustinLH

I had to start a new post since I didn't get a response from sfdcfox. Here is the link to that new thread:

 

http://boards.developerforce.com/t5/Apex-Code-Development/User-Lookup-Owner-Change-Trigger-Modification/td-p/395819

 

 

Here is the code that I ended up using (from that same thread):

 

trigger ReferralAssignOwner on Referral__c(before insert, before update) {
	
	if(Trigger.isBefore) {
	
		if(Trigger.isInsert) {
			
			for(Referral__c r: Trigger.New) {
			
				if(r.Assigned__c == null) {
				
					r.Assigned__c = UserInfo.getUserId();	
				}
					
				r.OwnerId = r.Assigned__c;		
				
			}
			
		}
		else if(Trigger.isUpdate) {
			
			for(Referral__c r: Trigger.New) {
			
				if(r.OwnerId != Trigger.oldMap.get(r.id).OwnerId) {
					
					r.Assigned__c = r.OwnerId;
						
				}
				else if(r.Assigned__c != Trigger.oldMap.get(r.id).Assigned__c) {
					
					if(r.Assigned__c == null) { // If the Assignee had been changed to NULL 
						r.Assigned__c = UserInfo.getUserId();	
					}
					
					r.OwnerId = r.Assigned__c;
				}
				
			}
			
		}
		
	}
	
	
	
}

 

cymartzcymartz

That worked great,

 

Can you help me modify my test script though? I continue to receive this error, which I noticed you referenced above:

System.AssertException: Assertion Failed: Expected: null, Actual: 005400000016MvaAAE

@isTest
private class testCritiqueChangeOwner {
  static testMethod void test() {
    List<User> testUsers = [SELECT id FROM user WHERE IsActive = true LIMIT 2];
        List<Call_Critique__c> refs = new List<Call_Critique__c>();
    refs.add(new Call_Critique__c(Need_Dialogue__c='Exceptional',Action_Close__c='Exceptional',Exit__c='Exceptional',Follow_Up__c='Exceptional',Objection_Resolution__c='Exceptional',Opening__c='Exceptional',Six_Critical_Skills__c='Exceptional',Solution_Dialogue__c='Exceptional',Structure__c='Exceptional',Supporting_Details__c='Exceptional',User__c=testUsers[0].Id));
    refs.add(new Call_Critique__c(Need_Dialogue__c='Exceptional',Action_Close__c='Exceptional',Exit__c='Exceptional',Follow_Up__c='Exceptional',Objection_Resolution__c='Exceptional',Opening__c='Exceptional',Six_Critical_Skills__c='Exceptional',Solution_Dialogue__c='Exceptional',Structure__c='Exceptional',Supporting_Details__c='Exceptional',User__c=testUsers[1].Id));
    insert refs;
    
      Map<Id, Call_Critique__c> refMap = new Map<Id, Call_Critique__c>([SELECT Id, User__c, OwnerId FROM Call_Critique__c WHERE Id IN :refs]);
    
    system.assertEquals(refs[0].OwnerId,testUsers[0].Id); // OwnerId should equal User__c;
    system.assertEquals(refs[1].OwnerId,testUsers[1].Id); // OwnerId should equal User__c;
    refs[0].OwnerId = testUsers[1].Id;
    refs[1].User__c = testUsers[0].Id;
    update refs;
    
       Map<Id, Call_Critique__c> refMap2 = new Map<Id, Call_Critique__c>([SELECT Id, User__c, OwnerId FROM Call_Critique__c WHERE Id IN :refs]);
    
    system.assertEquals(refs[0].User__c,testUsers[1].Id); // User__c should equal OwnerId now
    system.assertEquals(refs[1].OwnerId,testUsers[0].Id); // OwnerId should equal User__c now
  }  
}

 


DustinLHDustinLH

I am not great at writing test code yet, but here is the link to the thread about the test class troubles I had:

http://boards.developerforce.com/t5/Apex-Code-Development/system-assertEquals-Failure-on-Test-Class/m-p/395793#M70993

 

And here is the code that I finally ended up with for my test class:

 

@isTest
private class testReferralAssignOwner {
  static testMethod void test() {
    List<User> testUsers = [select id from user where isactive = true limit 2];
    
    Account a = new Account(Name='test');
    insert a;
    
    List<Referral__c> refs = new List<Referral__c>();
    refs.add(new Referral__c(Client_Name__c=a.id,Phone__c='12345',Assigned__c=testUsers[0].Id));
    refs.add(new Referral__c(Client_name__c=a.id,Phone__c='12345',Assigned__c=testUsers[1].Id));
    insert refs;

    Map<Id, Referral__c> refMap = new Map<Id, Referral__c>([SELECT Id, Assigned__c, OwnerId FROM Referral__c WHERE Id IN :refs]);

    system.assertEquals(refMap.get(refs[0].Id).OwnerId,testUsers[0].Id); // OwnerId should equal Assigned__c;
    system.assertEquals(refMap.get(refs[1].Id).OwnerId,testUsers[1].Id); // OwnerId should equal Assigned__c;
    refs[0].OwnerId = testUsers[1].Id;
    refs[1].Assigned__c = testUsers[0].Id;
    update refs;
    
    Map<Id, Referral__c> refMap2 = new Map<Id, Referral__c>([SELECT Id, Assigned__c, OwnerId FROM Referral__c WHERE Id IN :refs]);
    
    system.assertEquals(refMap2.get(refs[0].Id).Assigned__c,testUsers[1].Id); // Assigned__c should equal OwnerId now
    system.assertEquals(refMap2.get(refs[1].Id).OwnerId,testUsers[0].Id); // OwnerId should equal Assigned__c now
  }  
}