+ Start a Discussion
Chris Walters 9Chris Walters 9 

getting role of owner of a Task

Given a Task has a OwnerId that ties to a User, and
User has a UserRoleId field that ties to a UserRole, and
UserRole has a string Name field, I'd like to extract the role of the owner of a given task. This loads without error:
public String getRoleOfOwner( Task task) {
    User user = [SELECT Id FROM User WHERE Id = :task.ownerId];
    UserRole roleObj = [SELECT Id FROM UserRole WHERE Id = :user.UserRoleId]; 
    return roleObj.Name;

But that seems so old-school and unnecessary. Isn't there some dot-notation like
String roleOfOwner = task.OwnerId.User.UserRole.Name

where I can get the value directly?


Chris , SF Developer Day 20
Agustin BAgustin B
Hi Chris, you can save one query doing this in line 2 User user = [SELECT Id,UserRole.Name FROM User WHERE Id = :task.ownerId];
I think you will only need one query to get this.

If it helps please mark as best answer, it may help others
Dave ShulmanDave Shulman
Does this not work?
public static String getRoleOfOwner (Task tsk){
        String RoleName = Tsk.Owner.UserRole.Name;
        return RoleName;
Chris Walters 9Chris Walters 9
This does, Thanks!

Further learning: I see in Workbench that field OwnerId in Task has a relationshipName of Owner. But AccountId in Task has a relationshipName of Account. So in Apex coding I should be using the relationshipName of a field when that field is a Lookup to another sObject, correct?