How can I reference the owner first name from an sObject in Apex?

Below I'm trying to concatenate the date and Owner name fields from an sObject

    wdCreate.Name = string.valueOf(currentActivity.Work_Date__c) + 
    ': ' + currentActivity.OwnerId.FirstName + 
    ' ' + currentActivity.OwnerId.LastName;
  • 4
    use Owner.FirstName and Owner.LastName – Vigneshwaran G May 20 '16 at 20:30
  • 2
    * Owner.FirstName & " " & Owner.LastName – Dan Wooding May 20 '16 at 20:37
  • ahhh yes. I was relying on intellisense and was somewhat confused by not being able to find it. – tjcinnamon May 20 '16 at 20:41

Using the currentActivity.OwnerId reference is somewhat similar to using the __c suffix on a custom lookup or master detail field, the data you would receive back is the Id of that record rather than the object itself, in the case of the Owner field you need to use the currentActivity.Owner.FirstName syntax to reference fields on the owner record as you would use the __r.ExampleField syntax.

One thing to note with the above approach however is that the record owner for many objects including Leads within salesforce can be either a queue or a user. Therefore if you are looking to get FirstName of a Queue owner you will retrieve "null" for both the first and last name fields. You could write a small check into your code to mitigate this circumstance, something along the lines of the following would work nicely:

//If the owner of the record is a User (denoted by the 005 prefix to the Id)
//then we can use the first and last name, else use the .Name field from the queue.
if(((String)currentActivity.OwnerId).substring(0,3) == '005')
    wdCreate.Name = string.valueOf(currentActivity.Work_Date__c) + 
        ': ' + currentActivity.Owner.FirstName + 
        ' ' + currentActivity.Owner.LastName;
    wdCreate.Name = string.valueOf(currentActivity.Work_Date__c) + 
        ': ' + currentActivity.Owner.Name;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.