+ Start a Discussion
Zhenyu LiuZhenyu Liu 

Trigger to update lookup field with the value put in specific field

Hello Team,

I am not a developer and I do not yet write Apex code very well. I need an Apex Trigger to do the following:

whenever user put a value in the Change_Manager_field__c field which in User object, the manager field (standard field) need to be upated to the value which put in the Change_Manager_field__c.

Thanks in advance.
Best Answer chosen by Zhenyu Liu
Neetu_BansalNeetu_Bansal
Hi Zhenyu,

Yes you need to assign the managerid. Use the below code:
trigger userTrg on User(  before insert )
{
	for( User u : trigger.new )
	{
		if( u.Change_Manager_field__c != null )
			u.ManagerId = u.Change_Manager_field__c;
	}
}
Let me know, if you need any other help.

Thanks,
Neetu

All Answers

Neetu_BansalNeetu_Bansal
Hi Zhenyu,

I am supposing that your custom field is also a look up to User. Use the below code:
trigger userTrg on User(  before insert, before update )
{
	for( User u : trigger.new )
	{
		if( u.Change_Manager_field__c != null )
			u.Manager = u.Change_Manager_field__c;
	}
}
Let me know, if you need any other help.

Thanks,
Neetu
Zhenyu LiuZhenyu Liu
Hi Neetu, 

Thanks for your response, but after I put your code. it shows "Error: Compile Error: Illegal assignment from Id to User at line 6 column 13". The Change_Manager_field__c and manager field are both lookup to User.

Thanks
Zhenyu

 
Pramodh KumarPramodh Kumar
Could you please try to use below code and let me if you need any other help.

 
trigger userTrg on User(  before insert, before update )
{
	for( User u : trigger.new )
	{
		if( u.Change_Manager_field__c != null )
			u.Managerid = u.Change_Manager_field__c;
	}
}

Thanks,
Pramodh
Neetu_BansalNeetu_Bansal
Hi Zhenyu,

Yes you need to assign the managerid. Use the below code:
trigger userTrg on User(  before insert )
{
	for( User u : trigger.new )
	{
		if( u.Change_Manager_field__c != null )
			u.ManagerId = u.Change_Manager_field__c;
	}
}
Let me know, if you need any other help.

Thanks,
Neetu
This was selected as the best answer