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
apelizzo1.3941015382362622E12apelizzo1.3941015382362622E12 

How to create an Apex trigger to copy from one lookup field to another within the same object?

To manage Internal Support a new custom object has been created (Helpdesk__c). When a New Helpdesk record is created, the Helpdesk.Owner and the Helpdesk.Contact must be the same. How to create an Apex trigger to copy from Helpdesk.Owner to Helpdesk.contact since they are both lookup fields?

Thank you.
Adelchi
RitikaBhrgvRitikaBhrgv
Hi Adelchi,

Since you need to update the same record, it is best advisable to use before insert trigger. However, if Owner is standard field, you can utilize Userinfo.getUserId() since Owner will not be available on before insert trigger. Also, note that the current logged in user is selected as the default owner of the records which are being inserted.

Hence, on before insert the logic will become:
Helpdesk.Contact = Userinfo.getUserId();

In case if Owner is a custom field, refer to the following code:
Helpdesk.Contact = Helpdesk.Owner;

Hope this helps 
apelizzo1.3941015382362622E12apelizzo1.3941015382362622E12
Thank you Ritika,

here is what I am getting from it (just to clarify the Custom Object Name is "Case__c" which contains the Custom Contact Lookup Field "Contact__c" and the Standard field "Owner"):
User-added image
Sure@DreamSure@Dream
Hi ,

do like this:

 trigger Helpdesk on case__c(before insert)
{
  for(Case__c newCase:Trigger.new)
  {
    newCase.contact__c=Userinfo.getUserId();
   }
}
apelizzo1.3941015382362622E12apelizzo1.3941015382362622E12
Yes it works! God bless you ;-)

Why in this line: <for(Case__c newCase:Trigger.new)> "Case" is with " __c"

While in the following line  <newCase.contact__c=Userinfo.getUserId();> "newCase.contact__c" is not newCase__c.contact__c" ?

Tha nk you for your help.