I'm trying to set some default values for contact fields based on which user is inserting the record into the database, but am coming up against a NullPointerException as the CreatedById is null before insert. Is there any other way I can evaluate the user creating the record before it is inserted into the database?

Here is my trigger:

trigger ContactTrigger on Contact (before insert,before update, after insert, after update, before delete, after delete) {
        if(Trigger.isInsert && Trigger.isBefore){
        else if(Trigger.isInsert && Trigger.isAfter){
        else if(Trigger.isUpdate && Trigger.isBefore){
        else if(Trigger.isUpdate && Trigger.isAfter){
        else if(Trigger.isDelete && Trigger.isBefore){
        else if(Trigger.isDelete && Trigger.isAfter){
        else if(Trigger.isUndelete && Trigger.isBefore){

and my simplified handler class:

public class ContactTriggerHandler {

        public static void handleBeforeInsert(List<Contact> newContacts) {

        private static void setDefaultValues(List<Contact> newContacts){
            Set<ID> userIds = new Set<ID>(); //Define empty set of user ids to use in SOQL query below        
            for(Contact con : newContacts){ //Loop through contacts to populate set of user ids
                userIds.add(con.CreatedById); //add user id of user who created the record
            Map<ID, User> userMap = new Map<ID,User>([Select ID,UserRole.Name from User Where Id IN :userIds]);
            //Query for, and generate a map to get the role of the user who created the record
            for(Contact con : newContacts){
                //My logic here based on the role of the user creating the contact

The problem is that CreatedById is null until the record is inserted into the database. Is there any other way I can evaluate the user inserting the record without having to do this in an after insert context? I have other logic that fires to create custom child objects after insert that are dependent upon the values I want to set with my before insert trigger.

I'm fairly new to apex and programming in general, so any help would be greatly appreciated.

1 Answer 1


A call to System.UserInfo.getUserId() will give you the ID of the currently executing user during any transaction. This should solve your problem because the CreatedById always receives this value once it gets inserted.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .