2

I have some logic where I need to iterate thru a bunch of Opportunities. I need to be able to determine when I hit a new Opportunity Owner ID.

I try:

String lastownerId = '';

for (Opportunity opportunity: opportunities) {
    if(opportunity.OwnerId == (lastownerId)) {
        ...
        ...

I get: System.StringException: Invalid id:

any tips?

3 Answers 3

8

Salesforce has an ID-type, so you could use Id lastownerId = null; instead. This has the big advantage of being 15/18 character id insensitive in comparison, using string type may get you false negatives depending on what the input-id's look like.

Right now, you're apparently comparing some non-id string with an id. You will definitely get the error you see if you compare for example "apples" with an actual id, right now you're comparing it to an empty string which is also an invalid id. Comparing a valid id to null will not generate an error and result in False being returned as you might expect.

1
  • 1
    Completely agree with this. I ran into an issue the other day where I had a Custom Setting with a string type for ID. The issue ended up being comparing an 18-digit Id with a 15-digit one like Martin describes. Definitely use the Id type whenever you can. Jan 2, 2013 at 21:31
2

Here you are comparing ID data type(opportunity.OwnerId) with String data type(lastownerId) value thats why you are getting this error.

There are 2 possible solutions -

1) either change lastownerId data type to Id like - 
       Id lastownerId = null;

2) OR convert opportunity.OwnerId to string first then compare;
1

You can't convert an empty String to an Id so the if-condition fails on first execution. Try changing the variable declaration to

Id lastOwnerId = null;

You must log in to answer this question.

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