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
Abhishek RayAbhishek Ray 

Creating trigger to populate Owner Name in Task object to a new field "Current Owner"

Hi All,

 

I am creating a trigger to pull the owner name instead of id to a new field called "Current Owner" in the activity object in Task. I created a trigger but it is showing me id again. Please help me. Is there any way other to achieve it. What I am doing wrong. Please help with code and test class as I am new to trigger. Any help will be appreciated.

 

The problem here is I can't write in code: o.Current_Owner__c = o.Owner which is owner name but is is not allowing me save and giving some error.

 

Trigger:

trigger CurrentOwner on Task (before insert, before update) {

for(Task o:Trigger.new)

{o.Current_Owner__c = o.OwnerId;

}

}

 

Test Class:

public class CurrentOwner {

Public static void addCurrentOwner(Task[] acts) {

for(Task a:acts)

 {String Name = [Select id from User where ID = :a.ownerID].Name;a.Current_Owner__c = Name;

}}}

Damien_Damien_

You should be using o.Owner.Name instead of o.OwnerId.

 

You should use a formula field to do this instead of a trigger though.

Abhishek RayAbhishek Ray

The formula will not work. I can only populate owner id not the name. Can you tell how it can be done using formula?

Damien_Damien_

If you can't get the Owner.Name, just requery for the record then.  You can get it that way.

 

Add a formula field that is simply

 

Owner.Name

Abhishek RayAbhishek Ray

I tried. Not working. Saying Field doesn't exist.

Damien_Damien_

My bad, it doesn't let you use Owner in the formula field.  You don't actually want Owner.Name, you want Owner.Username in your trigger.

 

Note-You may need to requery for the record in order to get it, which means that it won't work in your before insert.  You might have to make it after insert and actually update it there or cause it to update in a @future method.

Abhishek RayAbhishek Ray

Hi, can you please in details? I didn't understand as I am new in apex programming.

Damien_Damien_

In the search bar, search for @future methods.  The below will only work on the before update.  The rest you will have to experiment with for the insert portion of the trigger.

 

trigger CurrentOwner on Task (before insert, before update)
{
	Map<Id, Task> taskMap = [SELECT Owner.UserName FROM Task WHERE Id IN :Trigger.new];
	for(Task o: Trigger.new)
	{
		o.Current_Owner__c = taskMap.get(o.Id).Owner.UserName;
	}
}