What is the best way to check whether lead belongs to Queue or User?

I’m trying to determine in a trigger, whether a lead belongs to a Queue or a User. What is the best way of going about this?

I tried the method mentioned in a dev. force discussion:

System.debug( lead.Owner.type )

… but this consistently keeps fetching null.

Alternatively, I was trying to determine by first 3 characters of the OwnerId (005 for User, 00G for Queue). I tried using:

lead.OwnerId.substring( 3 ) == '005' 

Trying the above gets me Method does not exist or incorrect signature.

Any bright ideas here?

Thank you.

Answer

The easiest way to do so is to not rely on the key prefix. Instead, just ask salesforce what the type is:

if(lead.OwnerId != null) { // User is currently known
    if(lead.OwnerId.getSObjectType() == User.SObjectType) {
        // Owner is a user
    } else if(lead.OwnerId.getSobjectType() == Group.SObjectType) {
        // Owner is a group
    }
}

To use Owner.Type, you need a query first:

Lead[] records = [SELECT Owner.Type FROM Lead WHERE Id IN :Trigger.new];

Note: Owner ID isn’t always available in trigger context (e.g. Before Insert), because the owner isn’t assigned until later.

Attribution
Source : Link , Question Author : miCRoSCoPiC_eaRthLinG , Answer Author : Scott Blaine

Leave a Comment