+ Start a Discussion
Nico WrennNico Wrenn 

Trigger to auto-populate a lookup field before record is saved for the first time


I've noticed that some managed packages have the ability to auto-populate a lookup field with the current user, before the record is saved for the first time. I want to do this on a custom object we have. For example, if there is a required User lookup field that needs to be filled out, but it's almost always going to be the current user, how could I write a trigger/apex code to auto-populate the lookup with the current user?

I am a complete beginner to Apex code. Thanks in advance for any help!
If the user field is optional on the layout , you can do somehting like this assuming this is on account
Trigger trigName on Account (before insert){
for(account acc: Trigger.New){
if(acc.fieldname == null)
acc.fieldname = userinfo.getuserid();


Glyn Anderson 3Glyn Anderson 3

venkay-D's solution will populate the user field upon save.  The user will see the new record page layout.  If they leave the user field blank and hit Save, the trigger will automatically populate the field with the current user.  If that's what you need - we're done!

If you want the field to be pre-populated on the new record page layout before the user hits Save, then that's a different problem.  You can create a custom New button for the object and use URL hacks to pre-populate fields.  Ben McCarthy has an excellent tutorial on this technique here (http://www.salesforceben.com/salesforce-url-hacking-tutorial/).  One problem with the technique, however, is that it uses field IDs, which are somewhat hidden in Salesforce, and aren't the same between a production org and its sandboxes.  So, your custom button probably won't work in any sandboxes.  Also, I don't think these URL hacked buttons are supported in Lightning Experience.

Another option is to create a custom VisualForce page and use it as an override for the New action.  Then you pre-populate whatever you want!  The big disadvantage is that the layout will no longer be admin configurable.

Let us know if any of these ideas meet your requirement, or if you need more help.
Nico WrennNico Wrenn
Interesting. Is there any way to populate the lookup field that doesn't require URL hacks or a custom button?
Glyn Anderson 3Glyn Anderson 3
If you're tyring to pre-populate fields on the "new record" page, I don't think there's any other way.  I would be very interested if anyone else could post such a solution!