I want to extract a custom field value in a soql using createdby reference.

List<CaseComment> cc = [Select createdby.customField__c from caseComment];

The soql is failing to recognize the customField. Is this not allowed?

  • Please add any error message verbatim.
    – Adrian Larson
    Aug 3 '17 at 12:24

The audit fields that refer to the user object are of the Name data type; this data type represents a few standard fields you can get data from, because these fields can actually refer to things other than just users. For example, CaseComment records can be created by a Contact record (by virtue of the Self Service Portal or Community portals).

What this means is that you can only access a handful of certain standard fields designed to work with the Name data type. If you want custom data, you'll need to use TYPEOF, which is still a developer preview feature, or you'll need a separate query, in the usual fashion:

Map<Id, User> users = new Map<Id, User>();
CaseComment[] comments = [SELECT CreatedById FROM CaseComment];
for(CaseComment record: comments) {
  users.put(record.CreatedById, null);
users.putAll([SELECT CustomField__c FROM User WHERE Id = :users.keySet()]);
User commentUser;
for(CaseComment record: comments) {
  if((commentUser = users.get(record.CreatedById)) != null) {
    // Do something with commentUser
  • Makes sense. However my requirement was to iterate over CaseComment(list in Vf page) and display the customField value for each case comment. Hence a separate map would be required to display the value for each case comment.
    – starhunter
    Aug 3 '17 at 12:37
  • @starhunter Yes, you'll need the separate map, unfortunately. Using the design outlined above should be acceptable though.
    – sfdcfox
    Aug 3 '17 at 12:39

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.