+ Start a Discussion
Andrew Dahlkemper 12Andrew Dahlkemper 12 

Fill Account owner on Tasks

Hi all,

I've search around a ton and can't find an example trigger to do the following: I'd like to fill in a custom field (lookup user) on the Task object for who the Account owner is whenever a Task is created.

My use case is I just want a way to identify who is creating Tasks on Accounts that are not owned by them (bad sales rep! bad!).

My custom field on Tasks is called Account_Owner__c. I already have an Apex Class that I believe will work. Any suggestions?  Thank you!
Rebecca Hendricks 3Rebecca Hendricks 3
I think there are two ways you can do this depending on if this is a Before trigger or an After trigger.

Before trigger
You can access the UserID of the person who is creating the task by calling UserInfo.getUserID();  I had to do this myself.  Here is the snippet of code where I get the information:
String userID = UserInfo.getUserId();	//Get User Id for task owner
I then used it in a SOQL query, as I was trying to get the tasks that user created.  But I would imagine that you could do something like:
String userID = UserInfo.getUserId();
Account_Owner__c = userID;
If you're using something other than the ID (like that's the user's name), then you may need to do a SOQL query on the user's table to get the user's name, such as:
String userID = UserInfo.getUserID();
Account_Owner__c = [SELECT Name FROM User WHERE id = :userID];

After trigger
I believe since the task has already been created and entered into the SF database, the Created By field holds the information on who created that task, which would be the user. So you can merely assign that value to your field, something like this:
Account_Owner__c = CreatedById

Hope this helps