11

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.

2 Answers 2

23

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.

0
2

The reason why you get the error Method does not exist or incorrect signature is due to Substring being a method of the String class. You need to cast the owner id into a string and then check.

Have a look at the string methods here

On the documentation, there are also examples of how to convert other data types into strings or assign the id to a string variable. You also need to specify the startIndex and the endIndex in the Substring method, information that is available in the link I've provided.

3
  • Thank you Mihai. I had a feeling it was due to type casting errors. However, checking for the first 3 characters seems like a hackish solution. Lead.Owner.type would have been more elegant - any idea why it returns null? Apr 20, 2015 at 16:36
  • Lead owner is a polymorphic field and hence needs to be accessed differently. For more details read mightycoder.blogspot.com/2013/06/…
    – Anshul
    Apr 20, 2015 at 16:38
  • 2
    I was focusing more on your error, rather than providing an alternative. I think sfdcfox's answer is what you are looking for. At least you've learned why it threw the error. Apr 20, 2015 at 16:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .